Given an integer array, find a subarray with sum closest to zero. Return the indexes of the first number and last number.
Example
Given [-3, 1, 1, -3, 5], return [0, 2], [1, 3], [1, 1], [2, 2] or [0, 4]
Challenge
O(nlogn) time
思路:
发现要求nlogn之后,自然想到了排序;又看到了subarray sum,于是想到了哈希表求subarray O(n)的方法;于是想到了如下方法:
1.遍历数组,用哈希表hash[i]来记录,从0到第i个元素之和。O(n)
2.将哈希表根据value排序。O(nlogn)
3.遍历哈希表,对比相邻两个键值对的value之差,找出相差最小的两个元素,取出他们的key,即是答案
class Solution {
public:
/**
* @param nums: A list of integers
* @return: A list of integers includes the index of the first number
* and the index of the last number
*/
vector<int> subarraySumClosest(vector<int> nums){
// write your code here
vector<int> result;
unordered_map<int,int> mp;
vector<unordered_map<int, int>::iterator> vec;
int sum = 0;
for (int i = 0; i < nums.size(); i++) {
sum += nums[i];
mp[i] = sum;
}
for (auto i = mp.begin();i != mp.end(); i++) {
vec.push_back(i);
}
sort(vec.begin(),vec.end(),cmp);
int mi = INT_MAX;
int res1 = 0,res2 = 0;
for (int i = 0; i < vec.size()-1; i++) {
int sum = abs(vec[i+1]->second - vec[i]->second);
if (sum < mi) {
mi = sum;
res1 = min(vec[i]->first,vec[i+1]->first);
res2 = max(vec[i]->first,vec[i+1]->first);
}
}
if (res1 != res2) {
res1++;
}
result.push_back(res1);
result.push_back(res2);
return result;
}
static bool cmp(unordered_map<int,int>::iterator start,unordered_map<int,int>::iterator end) {
if (start->second <= end ->second) {
return true;
}
return false;
}
};