https://leetcode.com/problems/two-sum/description/
Solution 1. Sort the index according to its value using lambda expression and search. (6 ms)
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> idx(nums.size(),0);
for(int i=0; i<idx.size(); i++) idx[i] = i;
sort(idx.begin(), idx.end(), [&](int i, int j){return nums[i]<nums[j];});
for(int i=0, j=idx.size()-1; i<j;) {
int x = nums[idx[i]]+nums[idx[j]];
if(x == target) return {idx[i], idx[j]};
else if(x>target) j--;
else i++;
}
return {};
}
Solution 2. Use a map: target - nums[i] -> i. (12 ms)
vector<int> twoSum(vector<int>& nums, int target) {
if(nums.size()<2) return {};
unordered_map<int,int> mp;
mp[target-nums[0]] = 0;
for(int i=1; i<nums.size(); i++){
if(mp.count(nums[i])) return {mp[nums[i]], i};
else mp[target-nums[i]] = i;
}
return {};
}
No comments:
Post a Comment