zoukankan      html  css  js  c++  java
  • 560. Subarray Sum Equals K

    Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

    Example 1:

    Input:nums = [1,1,1], k = 2
    Output: 2
    

    Note:

    1. The length of the array is in range [1, 20,000].
    2. The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].

    方法1:双层遍历

    。。。 

    方法2:利用哈希表加一点数学推导

    class Solution {
    public:
        int subarraySum(vector<int>& nums, int k) {
            int n = nums.size();
            if (n == 0) return 0;
            unordered_map<int, int>sum_fre;
            sum_fre[0] = 1;
            int sum = 0;
            int res = 0;
            for (auto num: nums)
            {
                sum += num;
                // k = sum[0, j] - sum[0, i - 1] ===> sum[0, j] - k  其中i-1 < j; 
                // 遍历一遍,将所有的sum[0, j]存起来。若在哈希表中发现之前有满足上边式子的,则得到一个满足要求的连续序列
                if (sum_fre.find(sum - k) != sum_fre.end())
                    res += sum_fre[sum - k];
                sum_fre[sum]++;
            }
            return res;
        }
    };
  • 相关阅读:
    创建大顶堆
    大顶堆的实现
    二叉树的前序,中序,后序,层序实现
    链表实现多项式相加
    225. Implement Stack using Queues
    232. Implement Queue using Stacks
    JavaScript 实现队列操作
    Vue 路由守卫
    回文数 & {}[]() 符号判断

  • 原文地址:https://www.cnblogs.com/qiang-wei/p/12271492.html
Copyright © 2011-2022 走看看