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

    Problem statement:

    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].

    Solution: two level loop(AC), I am surprised it is accepted.

    The question comes from leetcode weekly contest 30. I solved it with a two level loop and it is accepted by OJ. It gave me the time is 379ms. Time complexity is O(n * n). I am very surprised that OJ accepted O(n * n) solution. But AC is not the end, Let`s optimize it!

    Time complexity is O(n * n), space complexity is O(1).

    class Solution {
    public:
        int subarraySum(vector<int>& nums, int k) {
            int cnt = 0;
            for(vector<int>::size_type ix = 0; ix < nums.size(); ix++){
                int sum = 0;
                for(vector<int>::size_type iy = ix; iy < nums.size(); iy++){
                    sum += nums[iy];
                    if(sum == k){
                        cnt++;
                    }
                }
            }
            return cnt;
        }
    };

    Solution two: prefix sum + hash table(AC)

    But AC is not the end, Let`s optimize it!

    It comes from Leetcode article. The key is also prefix sum. And also, it normally increases the space complexity for the reduction of time complexity. Similar problem: 523. Continuous Subarray Sum.

    The basic idea:

    • A hash table to put all prefix sum and the count of this sum. If two index i and j get the sum prefix sum, that means the sum between i and j is 0. The initialization of hash table is {0, 1} since the sum is 0 if we do nothing for the array.
    • Traverse from beginning to the end, for the prefix sum in i, we index by sum - k from hash table, and add the count of sum - k to final answer if it exists in hash table.

    Time complexity is O(n). Space complexity is O(n).

    class Solution {
    public:
        int subarraySum(vector<int>& nums, int k) {
            unordered_map<int, int> hash_table{{0, 1}}; // <sum, # of sum>
            int sum = 0;
            int cnt = 0;
            for(auto num : nums){
                sum += num;
                if(hash_table.count(sum - k)){
                    cnt += hash_table[sum - k];
                }
                hash_table[sum]++;
            }
            return cnt; 
        }
    };
  • 相关阅读:
    算法-对分查找(二分查找)C++实现
    Android Studio简单设置
    一起talk C栗子吧(第八回:C语言实例--素数)
    Maven生命周期
    java8_api_日期时间
    UITableviewcell的性能问题
    iOS开发25个性能调优技巧
    iOS9新特性
    iOS9 3DTouch、ShortcutItem、Peek And Pop技术一览
    iOS网络访问之使用AFNetworking
  • 原文地址:https://www.cnblogs.com/wdw828/p/6880770.html
Copyright © 2011-2022 走看看