leetcode之two Sum

来源:互联网 发布:.top域名好优化吗 编辑:程序博客网 时间:2024/05/17 08:37

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

源代码如下:

 public 
 public static int[] twoSum(int[] numbers, int target) {        if(numbers.length <= 1)        return null;        int[] result = new int[2];        Arrays.sort(numbers);        int n = numbers.length;        for(int i = 0, j = n - 1; i <= j;)        {                    if(numbers[i] == target - numbers[j])            {                            if(i < j){                    result[0] = i + 1;                     result[1] = j + 1;                }else{                    result[0] = j + 1;                    result[1] = i + 1;                }                break;            }else if(numbers[i] < target - numbers[j]){             System.out.println("ok12");                ++ i;            }else{             System.out.println("ok13");                j --;            }        }                return result;    }
 /* 如果不需要两个数的下标值,则可以先对数组排序,然后用两个指针i,j从数组的头尾同时遍历数组,如果num[i] + num[j] > target,则j --;如num[i] + num[j] < target, 则i ++;直到num[i] + num[j] == target.(注:该思路来源于《程序员编程艺术》) 代码如下: */ public static int[] twoSum(int[] numbers, int target) {        if(numbers.length <= 1)        return null;        int[] result = new int[2];        Arrays.sort(numbers);        int n = numbers.length;        for(int i = 0, j = n - 1; i <= j;)        {                    if(numbers[i] == target - numbers[j])            {                            if(i < j){                    result[0] = i + 1;                     result[1] = j + 1;                }else{                    result[0] = j + 1;                    result[1] = i + 1;                }                break;            }else if(numbers[i] < target - numbers[j]){             System.out.println("ok12");                ++ i;            }else{             System.out.println("ok13");                j --;            }        }                return result;    }
                                             
0 0
原创粉丝点击