当前位置: 首页 > article >正文

33.日常算法

1.螺旋矩阵

题目来源
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。

示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<vector<int>> dis = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        vector<vector<bool>> vis(matrix.size(), vector<bool>(matrix[0].size(), false));
        int diction = 0;
        int total = matrix.size() * matrix[0].size();
        vector<int> ret(total);
        int row = 0, col = 0;
        int idx = 0;
        for (int i = 0; i < total; ++i){
            ret[i] = matrix[row][col];
            vis[row][col] = true;
            int newrow = row + dis[idx][0], newcol = col + dis[idx][1];
            if (newrow >= matrix.size() || newcol >= matrix[0].size() || vis[newrow][newcol]){
                ++idx;
                idx %= 4;
            }
            row = row + dis[idx][0];
            col = col + dis[idx][1];
        }
        return ret;
    }
};

2. 和为 K 的子数组

题目来源
给你一个整数数组 nums 和一个整数 k ,请你统计并返回 该数组中和为 k 的子数组的个数 。子数组是数组中元素的连续非空序列。

示例 1:
输入:nums = [1,1,1], k = 2
输出:2

class Solution {
public:
    int subarraySum(vector<int>& nums, int k) {
        unordered_map<int, int> hash;
        hash[0] = 1; // 进行初始化
        int sum = 0;
        int ret = 0;
        for (auto & x : nums){
            sum += x;
            if (hash.count(sum - k)) ret += hash[sum - k];
            hash[sum]++;
        }
        return ret;
    }
};

http://www.kler.cn/a/538367.html

相关文章:

  • LeetCode 102. 二叉树的层序遍历题解
  • 【Python】元组
  • Windows逆向工程入门之汇编环境搭建
  • 力扣-字符串-28 找出字符串中第一个匹配项的下标
  • A股level2高频数据分析20250205
  • pytest+request+yaml+allure 接口自动化测试全解析[手动写的跟AI的对比]
  • Python进阶-在Ubuntu上部署Flask应用
  • iPhone 在华销量大幅下挫
  • STM32启动过程概述
  • Elasticsearch term精确查询无数据
  • Maven 依赖范围与排除
  • 如何训练开源模型成为专业业务模型
  • Racecar Gym 总结
  • DeepSeek训练成本与技术揭秘
  • android中关于CheckBox自定义选中图片选中无效问题
  • 京准:NTP卫星时钟服务器对于DeepSeek安全的重要性
  • ChatGPT搜索免费开放:AI搜索引擎挑战谷歌霸主地位全面分析
  • docker compose文件中的${}怎么赋值
  • uniapp 编译生成鸿蒙正式app步骤
  • JAVA安全—FastJson反序列化利用链跟踪autoType绕过
  • Composo:企业级AI应用的质量守门员
  • 四元数:连接四维时空与三维旋转的数学桥梁
  • 超越传统IDE:Cursor智能编码介绍
  • Mysql系列之--InnoDB存储引擎
  • 基于 Linux 与 CloudFlare 的智能实时 CC/DDoS 防御方案
  • Vue 3 30天精进之旅:Day 18 - 测试Vue组件