title: Leet Code TwoSum
date: 2017-07-08 23:18:54
tags:
- LeetCode
- 算法
categories: 算法
題目:
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].
第一反應可以把nums循環(huán)兩次湾盒,用n^2的時間復雜度
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
int n = numbers.size();
vector<int> ans;
for (int i = 0; i < n-1; i++) {
for (int j = i + 1; j < n; j++) {
if (numbers[i] + numbers[j] == target) {
ans.push_back(i);
ans.push_back(j);
return ans;
}
}
}
return ans;
}
};
后來想到可以把每個數(shù)字放到Map里雹有,總的時間復雜度可以到n膊毁。
class Solution{
public:
vector<int> twoSum(vector<int>& numbers, int target) {
map<int, int> mymap;
int n = numbers.size();
vector<int> ans;
for(int i=0;i<n;i++){
int t = target - numbers[i];
if(mymap.count(t) > 0){
ans.push_back(mymap[t]);
ans.push_back(i);
return ans;
}else{
mymap[numbers[i]] = i;
}
}
return ans;
}
};
上面程序的運行時間是9ms,打敗了54.67% 。
后來看了前排6ms的代碼,發(fā)現(xiàn)只是把map換成了unorder_map
,因為map是紅黑樹實現(xiàn)的凰慈,會根據(jù)鍵的大小排序,查找的時間復雜度是n驼鹅,而unorder_map
沒有排序微谓,是hash實現(xiàn)的,查找的時間復雜度是常數(shù)級输钩,因此會更快豺型。