//1.暴力拆解
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res;
for(int i=0;i<nums.size()-1;i++){
for(int j=i+1;j<nums.size();j++){
if(nums[i]+nums[j]==target){
res.push_back(i);
res.push_back(j);
return res;
}
}
}
return res;
}
};
//2.哈希表
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
map<int,int> mid;
vector<int> res;
int i,j;
for(i=0;i<nums.size();i++){
mid[nums[i]]=i;//给哈希表赋值
}
for(j=0;j<nums.size();j++){
if(mid.count(target-nums[j])>0 && mid[target-nums[j]]!=j){
res.push_back(j);//存在且不是本身
res.push_back(mid[target-nums[j]]);
break;
}
}
return res;
}
};
leetcode 1:两数之和(c++)
最新推荐文章于 2022-10-06 15:43:55 发布