暴力解法
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int i=0,j,flag = 0,n = nums.size();
while(i<n && flag ==0){
for(j=i+1;j<n;j++){
if(nums[j]+nums[i]==target){
flag = 1;
break;
}
}
if(!flag) i++;
}
return {i, j};
}
};
时间复杂度O(n²)
空间复杂度O(1)
优化->空间换时间->查找表->哈希表/平衡二叉搜索树
哈希表
计算target-nums[i]的值,若哈希表中没有则记录值和下标进入哈希表
若有,则找到。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> hashtable; // 建哈希表
vector<int> b(2,-1); //存放结果
for (int i = 0; i < nums.size(); i++) {
if(hashtable.count(target-nums[i])){
b[0]=hashtable[target-nums[i]];
b[1]=i;
break;
}
hashtable[nums[i]]=i;
}
return b;
}
};
用find(官方题解)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> hashtable;
for (int i = 0; i < nums.size(); ++i) {
auto it = hashtable.find(target - nums[i]);
if (it != hashtable.end()) {
return {it->second, i};
}
hashtable[nums[i]] = i;
}
return {};
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
改进
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int, int> hashtable; // 建哈希表
for (int i = 0; i < nums.size(); i++) {
auto a = hashtable.find(target-nums[i]);
if(a!=hashtable.end()){ //找到了
return{a->second,i};
}
hashtable[nums[i]]=i;
}
return {};
}
};