Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
上面是题目原文。
解一: 先用快排将numbers升序排序(O(nlogn));然后用两个指针分别从两端往中间夹逼(O(n));
上代码:
/*
* O(nlogn)
*/
import java.util.ArrayList;
import java.util.Collections;
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] ans = new int[2];
ArrayList arrayList = new ArrayList<Node>();
for(int i=0; i<numbers.length; i++){
arrayList.add(new Node(i+1, numbers[i]));
}
<span style="white-space:pre"> </span>//排序
Collections.sort(arrayList);
<span style="white-space:pre"> </span>//夹逼
for(int i=0,j=arrayList.size()-1; i != j; ){
Node nodeI = (Node)arrayList.get(i);
Node nodeJ = (Node)arrayList.get(j);
int sum = nodeI.getValue() + nodeJ.getValue();
if (sum > target) {
j --;
}
else if (sum < target) {
i++;
}
else {
ans[0] = minOfTwo(nodeI.getPos(), nodeJ.getPos());
ans[1] = maxOfTwo(nodeI.getPos(), nodeJ.getPos());
break;
}
}
return ans;
}
class Node implements Comparable<Object>
{
private int pos;
private int value;
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return this.value-((Node)o).value;
}
public Node(int pos, int value) {
super();
this.pos = pos;
this.value = value;
}
public int getPos() {
return pos;
}
public void setPos(int pos) {
this.pos = pos;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
private int minOfTwo(int a,int b) {
return a>b? b:a;
}
private int maxOfTwo(int a,int b) {
return a>b? a:b;
}
}
解二: 将numbers数组的所有元素以值为key,以该值在numbers数组中的索引值作为value存进一个HashTable对象。
然后遍历numbers数组,对每个元素v,根据key=target-v到HashTable中get。如果返回null,说明该元素不是我们要找的;如果返回了非null的值w,则[v,w]数组就是答案了。
另外需要注意到,可能numbers中恰好有值为target/2的元素。我在代码中对该情况做看特别处理。
上代码:
/*
* O(n)
*/
import java.util.Hashtable;
public class Solution {
public int[] twoSum(int[] numbers, int target) {
int[] ans = new int[2];
Hashtable hashtable = new Hashtable();
for(int i=0; i<numbers.length; i++){
hashtable.put(numbers[i], i);//
}
for(int i=0; i<numbers.length; i++){
//判断结果是否为两个等值元素
if (numbers[i]+numbers[i] == target) {
for(int j=i+1; j<numbers.length; j++){
if (numbers[i] == numbers[j]) {
ans[0] = i+1;
ans[1] = j+1;
return ans; //特殊情况,任务完成
}
}
}
Object index = hashtable.get(target-numbers[i]);
if (index != null) {
int ans1 = i;
int ans2 = (int)index;
if (ans1 == ans2) {
continue;
}
ans[0] = minOfTwo(ans1+1, ans2+1);
ans[1] = maxOfTwo(ans1+1, ans2+1);
break;
}
}
return ans;
}
private int minOfTwo(int a,int b) {
return a>b? b:a;
}
private int maxOfTwo(int a,int b) {
return a>b? a:b;
}
}