leetcode 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:
The length of the array is in range [1, 20,000].
The range of numbers in the array is [-1000, 1000] and the range of the integer k is [-1e7, 1e7].
解题思路
一个很简单的想法就是暴力求解了,直接一个循环嵌套结束,但很明显这种解法不会满足面试要求。我们知道,题解的关键在于范围[i,j]的确定若 sum(i,j) = k ,则必有
sum(0,j)-sum(0,i) = k
因此,我们只需要记录每一次叠加求和后的值即可,这样得到的前置求和序列,若与k相减得到的数也存在于序列中,即说明上式成立,根据上述思路写出的代码如下:
class Solution {
public:
int subarraySum(vector<int>& nums, int k) {
unordered_map<int,int> mMap;
mMap[0] = 1;
int sum = 0;
int result = 0;
for(auto&val:nums) {
sum+=val;
result += mMap[sum-k];
mMap[sum]++;
}
return result;
}
};
使用unordered_map(C++11)的目的在于对于无序存储的序列,hash方式的map速度更快。
leetcode 1. Two Sum
写在前面
本题与上一题基本是一样的,都是记录下preValue,然后用map的查找即可,因此代码也基本一致,这里把他们作为同一种类型的题目整理。这种解法的效率是O(n),只需要循环遍历一次数组。若本题改成排序后的数组,更快的解法是从数组两侧进行遍历求和。
题目描述
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解题思路
直接使用与560相同的解法。
代码如下:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
if(nums.empty()) return {};
unordered_map<int,int> mHashMap;
for(int i = 0;i<nums.size();++i) {
auto val = target-nums[i];
if(mHashMap.find(val)!=mHashMap.end()) {
return {mHashMap[val],i};
}
mHashMap[nums[i]] = i;
}
return {};
}
};