- 双指针
- 复杂度=O(n+nlogn+n+n) = O(nlogn)。
import java.util.*;
public class MyDemo{
public static boolean hassum(int[] A,int target){
boolean res=false;
if(A==null||A.length<2)
return res;
Arrays.sort(A);
int i=0,j=A.length-1;
while(i<j){
if(A[i]+A[j]==target){
res=true;
break;
}else if(A[i]+A[j]>target){
j--;
}else{
i++;
}
}
return res;
}
public static void main(String agrs[])
{
int[] A = {0,4,3,0};
int target = 5;
boolean result = hassum(A, target);
System.out.println(result);
}
}
import java.util.HashMap;
import java.util.Scanner;
public class Solution {
public static int[] twoSum(int[] numbers, int target) {
int[] res = new int[2];
HashMap<Integer, Integer> nums = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; ++i) {
Integer a = nums.get(numbers[i]);
if (a == null)
nums.put(numbers[i], i);
a = nums.get(target - numbers[i]);
if (a != null && a<i ) {
res[0] = a + 1;
res[1] = i + 1;
break;
}
}
return res;
}
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
int n = cin.nextInt();
int[] numbers = new int[n];
for (int i = 0; i < numbers.length; ++i) {
numbers[i] = cin.nextInt();
}
int target = cin.nextInt();
int[] res = twoSum(numbers, target);
System.out.println(res[0] + " " + res[1]);
}
}
c++版本
#include<iostream>
#include<vector>
#include<map>
#include <hash_map>
using namespace std;
using namespace stdext;
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
hash_map<int, int> rec;
vector<int> ret;
int s = numbers.size();
for (int i = 0; i < s; ++i)
rec.insert(pair<int, int>(numbers[i], i + 1));
for (int i = 0; i < s; ++i){
int v = numbers[i];
hash_map<int, int>::iterator iter = rec.find(target - v);
if (rec.end() != iter && iter->second <(i+1)){
int j = iter->second;
if (i < j) {ret.push_back(i+1); ret.push_back(j);}
else {ret.push_back(j); ret.push_back(i+1);}
return ret;
}
}
return ret;
}
};
int main(int ac, char* av[])
{
Solution s;
vector<int> testTwoSum;
int n,t;
cin >> n;
while(n--){
cin>>t;
testTwoSum.push_back(t);
}
int target;
cin>>target;
vector<int> res=s.twoSum(testTwoSum,target);
for (vector<int>::iterator it=res.begin(); it!=res.end(); it++){
cout<<*it<<endl;
}
return 0;
}