Two Sum

来源:互联网 发布:js 集合:{} 编辑:程序博客网 时间:2024/04/28 13:45

Mar 14 '11

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

记录原始下标,然后排序。由于是有序的,如果当前和大于target,那么只有增大start下标才有可能得出解。同理,当和小于target时,只有减小end才有可能得到解。排序所用时间O(nlogn),之后的判断O(n)。总的时间复杂度为O(nlogn)


import java.util.Arrays;class Pair implements Comparable<Pair>{public int val;public int index;@Overridepublic int compareTo(Pair o) {return this.val-o.val;}}public class Solution {public int[] twoSum(int[] numbers, int target) {Pair pairs[] = new Pair[numbers.length]; for(int i=0;i<numbers.length;++i){ pairs[i] = new Pair();pairs[i].index = i;pairs[i].val = numbers[i];} Arrays.sort(pairs); int i=0, j=numbers.length-1; while(i < j){ int sum = pairs[i].val + pairs[j].val; if( sum == target){ int[] res = new int[2]; res[0] = Math.min(pairs[i].index, pairs[j].index) + 1; res[1] = Math.max(pairs[i].index, pairs[j].index) + 1; return res; }else if(sum > target) j--; else i++;  } return null;}/*public static void main(String[] args) {//[5,75,25], 100int[] array = {2, 7, 11, 15};Solution solution = new Solution();System.out.println(Arrays.toString(solution.twoSum(array, 9)));}*/}



原创粉丝点击