题目
思路
起初,用find找直接超时,官网题解,用双指针。哎。。。
双指针很经常用到的!!
迭代器与下标转换
记录个小知识点
用find函数,返回的是迭代器,要求的是需要下标,可以用迭代器减去数组起始就是下标
auto it=find(nums.begin(),nums.end(),temp);
int index=it-nums.begin()
C++代码
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
vector<int> twoSum(vector<int>& numbers, int target) {//超出时间限制
int size = numbers.size();
auto begin=numbers.begin(),end=numbers.end();
vector<int> ret;
for(int i=0;i<size;i++){
int temp=target-numbers[i];
auto it=find(begin+i+1,end,temp);
if(it!=end){
ret.emplace_back(i+1);
ret.emplace_back(it-begin+1);
break;
}
}
return ret;
}
vector<int> twoSum1(vector<int>& numbers, int target) {//双指针
vector<int> ret;
int i=0,j=numbers.size()-1;
while(i<j){
int sum=numbers[i]+numbers[j];
if(target==sum){
ret.emplace_back(i+1);
ret.emplace_back(j+1);
break;
} else if(target>sum){
i++;
} else j--;
}
return ret;
}
int main(){
int size=0,target=0;
cin>>size;
vector<int> nums(size);
for(int i=0;i<size;i++) cin>>nums[i];
cin>>target;
vector<int> ret=twoSum1(nums,target);
cout<<ret[0]<<" "<<ret[1]<<endl;
return 0;
}
9.3 更
Java
//哈希表关联
class Solution {
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> hashMap=new HashMap<Integer, Integer>();
int len=numbers.length;
for(int i=0;i<len;i++){
if(hashMap.containsKey(target-numbers[i])){
return new int[]{hashMap.get(target-numbers[i]), i+1};
}
hashMap.put(numbers[i], i+1);
}
return new int[0];
}
}
//双指针
class Solution {
public int[] twoSum(int[] numbers, int target) {
int tail=numbers.length-1, head=0;
while(head<tail){
if(numbers[head]+numbers[tail]>target){
tail--;
} else if(numbers[head]+numbers[tail]<target){
head++;
} else{
return new int[]{head+1, tail+1};
}
}
return new int[0];
}
}