Two Sum
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
麻烦的地方在于输出的是index,所以要在排序前先保存其原始index。
1 public class Solution { 2 public class Element{ 3 int number; 4 int index; 5 public Element(int n, int i){ 6 this.number = n; 7 this.index = i + 1; 8 } 9 } 10 public int[] twoSum(int[] numbers, int target) { 11 // Note: The Solution object is instantiated only once and is reused by each test case. 12 Element[] num = new Element[numbers.length]; 13 for(int i = 0; i < numbers.length; i ++){ 14 num[i] = new Element(numbers[i], i); 15 } 16 Arrays.sort(num, new Comparator<Element>(){ 17 public int compare(Element o1,Element o2){ 18 return o1.number > o2.number ? 1 : (o1.number == o2.number ? 0 : -1); 19 } 20 }); 21 int i = 0; 22 int j = numbers.length - 1; 23 while(i < j){ 24 int sum = num[i].number + num[j].number; 25 if(sum == target){ 26 return new int[]{Math.min(num[i].index, num[j].index), Math.max(num[i].index, num[j].index)}; 27 }else if(sum < target){ 28 i ++; 29 }else{ 30 j --; 31 } 32 } 33 return new int[]{-1,-1}; 34 } 35 }
posted on 2013-10-22 14:51 Step-BY-Step 阅读(190) 评论(0) 编辑 收藏 举报