明明的leetcode日常:1. Two Sum
最近一直在科研科研科研,好久沒有刷題手生了,我又不願意給我的mac裝vs所以只好在vim裡盲寫。leetcode第一題都做了一小時【暈。
題幹:
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].
我的思路:排序,然後頭尾安插迭代器,往中間靠攏,加到合適的為止。這個方法的時間複雜度取決於sort函式排序的效率,時間複雜度估計是nlogn。最後跑下來大概是在54.29%的位置。
class Solution {
public:
static bool compare(const pair<int,int> a,const pair<int,int> b)
{
return a.first>b.first;
}
vector<int> twoSum(vector<int>& nums, int target) {
vector< pair<int,int> > nums2;
//兩個“>”之間注意加空格
int i=0;
for(auto data:nums)
{
pair<int,int> temp;
temp=make_pair(data,i);
nums2.push_back(temp);
++i;
}
sort(nums2.begin(),nums2.end(),compare);
vector <int> result;
auto start_point=nums2.begin();
auto end_point=nums2.end(); --end_point;
while(start_point<end_point)
{
int sum=(*start_point).first+(*end_point).first;
if(sum>target) ++start_point;
else if(sum<target) --end_point;
else
{
if((*start_point).second<(*end_point).second)
{
result.push_back((*start_point).second);
result.push_back((*end_point).second);
}
else
{
result.push_back((*end_point).second);
result.push_back((*start_point).second);
}
++start_point;
--end_point;
}
}
return result;
}
};
我的思路變化過程:後來我想有沒有更好的方法,我想用map,但是map本質上也是紅黑樹排序,時間複雜度也不比sort低,而且我一開始的思路是,將容器中所有的元素都存放在map中,然後在map中查詢,但是我面臨了一個問題:[3,2,3]這種資料怎麼處理?
其實我忽略了一個關鍵的細節:答案唯一,也就是說只有一對數滿足要求,找到這一對就沒有往下找的必要了。於是,大神的方法是,在map中邊插入元素邊檢索,找到了直接停止,沒找到就繼續插入繼續找。
為了加快速度,大神用unordered_map代替map,因為unordered_map內部是用雜湊表實現的,也就是說,雜湊得好的話,它的時間複雜度是比map低的。
大神的方法:
vector<int> twoSum(vector<int> &numbers, int target)
{
//用雜湊鍵值對查詢,鍵是原先提供的數字,值是數字在原容器中的下標
unordered_map<int, int> hash;
vector<int> result;
for (int i = 0; i < numbers.size(); i++) {
int numberToFind = target - numbers[i];
//直接查詢之前儲存在雜湊表中的元素有沒有可以與當前元素匹配的
//如果有這樣的元素,由於本題的答案唯一,因此可以直接返回值
if (hash.find(numberToFind) != hash.end()) {
result.push_back(hash[numberToFind]);
result.push_back(i);
return result;
}
//如果找不到與當前數匹配的鍵,就將當前數插入雜湊表中,等待被後續的數檢索
hash[numbers[i]] = i;
}
return result;
}