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].
解法 :
顧名思義就是要你找出這個array中有兩個數字是符合你所給定的條件,當然這一題假設只有唯一解
解法有兩種 一個是 O(N^2) 另外一種是O(N)
第一種就類似sort的方式,我就不用再多說了。
第二種解法的邏輯是這樣
用一個hash值儲存你到目前為止所找到的值的index,在for中每當i+1,就跟回去hash中找有沒有跟
target - nums[i] 符合的值
程式碼如下
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> twoSumMap;
vector<int> answer;
for (int i = 0; i < nums.size(); i++)
{
if (twoSumMap.count(target - nums[i]) > 0)
{
answer.push_back(twoSumMap[target - nums[i]]);
answer.push_back(i);
break;
}
else
{
twoSumMap[nums[i]] = i;
}
}
return answer;
}
};
沒有留言 :
張貼留言