Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn’t one, return 0 instead.
Example 1:
Given nums = [1, -1, 5, -2, 3], k = 3,
return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest)
Example 2:
Given nums = [-2, -1, 2, 1], k = 1,
return 2. (because the subarray [-1, 2] sums to 1 and is the longest)
Follow Up:
Can you do it in O(n) time?
原题地址
利用hash table纪录nums[0]到nums[i]的和,寻找两个和的差等于k的最大距离。Time: O(n). Space: O(n).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
int (vector<int>& nums, int k) { unordered_map<int, vector<int>> hash; int run_sum = 0; for (int i = 0; i < nums.size(); i++) { run_sum += nums[i]; hash[run_sum].push_back(i); } int res = 0; if (hash.count(k) > 0) { res = hash[k].back() + 1; } for (auto& x : hash) { if (hash.count(x.first + k) > 0) { res = max(res, hash[x.first + k].back() - x.second[0]); } } return res; }
|
后来发现可以一边存入hash table一边比较,因为只需要和之前的数据求差即可。速度可以更快,代码更简洁。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
int (vector<int>& nums, int k) { unordered_map<int, int> hash; int run_sum = 0; int res = 0; for (int i = 0; i < nums.size(); i++) { run_sum += nums[i]; if (run_sum == k) { res = i + 1; } else if (hash.count(run_sum - k) > 0) { res = max(res, i - hash[run_sum - k]); } if (hash.count(run_sum) == 0) { hash[run_sum] = i; } } return res; }
|
近期评论