标签:pre time level ota ini order state exist orm
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:
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:
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; } };
标签:pre time level ota ini order state exist orm
原文地址:http://www.cnblogs.com/wdw828/p/6880770.html