给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。
你需要实现的函数twoSum
需要返回这两个数的下标, 并且第一个下标小于第二个下标。注意这里下标的范围是 1 到 n,不是以 0
开头。
注意事项
你可以假设只有一组答案。
样例
给出 numbers = [2, 7, 11, 15]
, target = 9
, 返回 [1, 2]
.
1 import java.util.Arrays; 2 3 /** 4 * Created by Tutotu on 2017/2/26. 5 * <p> 6 * Realname:yangmingzhu 7 * <p> 8 * Tel:18511400217 9 * <p> 10 * Email:[email protected] 11 */ 12 13 public class Solution11 { 14 /* 15 * @param numbers : An array of Integer 16 * @param target : target = numbers[index1] + numbers[index2] 17 * @return : [index1 + 1, index2 + 1] (index1 < index2) 18 */ 19 public int[] twoSum(int[] numbers, int target) { 20 // write your code here 21 int[] temp = Arrays.copyOf(numbers,numbers.length); 22 int heigh = 0; 23 int low = 0; 24 int[] location = new int[2]; 25 int i=0; 26 Arrays.sort(temp); 27 heigh = temp.length-1; 28 while(low < heigh && (temp[low] + temp[heigh] != target)){ 29 if(temp[low] + temp[heigh] < target){ 30 low++; 31 } 32 if(temp[low] + temp[heigh] > target){ 33 heigh--; 34 } 35 } 36 System.out.print(low + "" + heigh) ; 37 38 39 while(i<numbers.length && numbers[i] != temp[low]){ 40 i++; 41 } 42 location[0] = i+1; 43 i = numbers.length-1; 44 while(i>0 && numbers[i] != temp[heigh]){ 45 i--; 46 } 47 location[1] = i+1; 48 Arrays.sort(location); 49 return location; 50 } 51 52 53 public static void print(int[] paramter){ 54 for(int i=0; i<paramter.length; i++) 55 System.out.print(paramter[i]); 56 } 57 public static void main(String[] args){ 58 int[] a = new int[]{0,4,3,0}; 59 print(new Solution11().twoSum(a,-1)); 60 } 61 }
时间: 2024-10-10 16:15:22