LeetCode題解 C++ Two Sum
阿新 • • 發佈:2019-02-10
最近要開始準備實習了,為了讓自己顯得不那麼弱,所以拾起了以前的A題的感覺,開始在大名鼎鼎的LeetCode上開始刷題,廢話不多說了,就從第一題開始吧。
1. Two Sum
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].
說實話重新開始做演算法題已經手生了,剛開始做沒有想很多,就開始暴力的用O(n^2)的方法,果然不出所料超時了.
原來思路是,對原來的陣列做一個排序,然後兩邊的數往中間夾逼.程式碼如下
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector <int> numbers = nums;
std::sort(numbers.begin(), numbers.end());
int length = numbers.size();
int left = 0;
int right = length - 1;
int sum = 0;
vector<int> index;
while(left < right)
{
sum = numbers[left] + numbers[right];
if (sum == target)
{
for(int i = 0; i < length; ++ i)
{
if(nums[i] == numbers[left])
{
index.push_back(i + 1);
}
else if(nums[i] == numbers[right])
{
index.push_back(i + 1);
}
if(index.size() == 2)
break;
}
}
else if(sum > target)
{
right --;
}
else
{
left ++;
}
}
return index;
}
};
思考了一會才想到,原來的hash方法其實可以把時間縮短到O(n).
具體思路是我把原來的陣列用map記錄下來,每次記錄時比較值和target的差值,如果在map中可以找到,就實現匹配,縮短時間.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> m;
vector<int> index;
for(int i = 0; i < nums.size(); ++ i)
{
if(m.count(target - nums[i]) != 0)
{
index.push_back(m[target - nums[i]]);
index.push_back(i);
break;
}
m[nums[i]] = i;
}
return index;
}
};
加油繼續A題……/(ㄒoㄒ)/~~