實現:java
import java.util.*; public class Solution { public int[] twoSum(int[] numbers, int target) { int[] t=new int[2]; ArrayList<Node> l=new ArrayList<Node>(); for(int i=0;i<numbers.length;i++){ l.add(new Node(i,numbers[i])); } l.sort(new Comparator<Node>(){ @Override public int compare(Node arg0, Node arg1) { return arg0.value-arg1.value; } }); for(int s=0,e=numbers.length-1;s<e;){ if(l.get(s).value+l.get(e).value==target){ if(l.get(s).index<l.get(e).index){ t[0]=l.get(s).index; t[1]=l.get(e).index; }else{ t[1]=l.get(s).index; t[0]=l.get(e).index; } return t; }else if(l.get(s).value+l.get(e).value<target){ s++; }else{ e--; } } return t; } } class Node{ int index; int value; public Node(int index, int value) { super(); this.index = index+1; this.value = value; } }