1. Two Sum
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
人家媳妇:
time \(O(n)\), space \(O(n)\)
方法中巧妙使用map,一次遍历完成任务.
遍历数组时,若未在map中找到想要的元素,则把数组中当前元素投入map.(注key=数组元素值,val=该元素indx)
vector<int> twoSum(vector<int> &numbers, int target) {
//Key is the number and value is its index in the vector.
map<int, int> hash; //原来人家用的是unordered_map
vector<int> result;
for (int unsigned i = 0; i < numbers.size(); i++) {
int numberToFind = target - numbers[i];
//if numberToFind is found in map, return them
if (hash.find(numberToFind) != hash.end()) {
//map 中若找到
//+1 because indices are NOT zero based
result.push_back(hash[numberToFind] + 1);
result.push_back(i + 1);
return result;
}
//number was not found. Put it in the map.
hash[numbers[i]] = i;
}
return result;
}
自家媳妇 😃
time \(O(n^2)\), space \(O(1)\)
Brute Force
class Solution {
public:
vector<int> twoSum(vector<int> nums, int target) {
vector<int> result;
for (int i = 0; i < nums.size(); i++)
for (int j = i + 1; j < nums.size(); j++)
if (nums[j] == target - nums[i]) {
result.push_back(i);
result.push_back(j);
}
return result;
}
};