比如:
输入: numbers={2, 7, 11, 15}, target=9
输出: index1=1, index2=2
1 public class _003TwoSum { 2 3 public static void main(String[] args) { 4 int a[]={3,22,4,7,8,22}; 5 6 display(twoSum3(a,30)); 7 } 8 //暴力搜索法 9 public static int[] twoSum(int[] numbers, int target) { 10 int index[] = {0,0}; 11 for(int i=0; i<numbers.length; i ++){ 12 for(int j=i+1; j<numbers.length; j++){ 13 if(target == numbers[i]+numbers[j]){ 14 index[0] = i+1; 15 index[1] = j+1; 16 return index; 17 } 18 } 19 } 20 return index; 21 22 } 23 24 //使用map,因为刚好是两个值,一个值一个下表map刚好可以储存然后用map的containsKey的方法 25 public static int[] twoSum2(int[] numbers, int target) { 26 int index[] = {0,0}; 27 HashMap<Integer, Integer> num = new HashMap<Integer,Integer>(); 28 for(int i=0;i<numbers.length;i++){ 29 num.put(numbers[i], i); 30 } 31 for(int i=0;i<numbers.length;i++){ 32 int temp = target-numbers[i]; 33 if(num.containsKey(temp)&&i<num.get(temp)){ 34 index[0] = i+1; 35 index[1] = num.get(temp)+1; 36 break; 37 } 38 } 39 return index; 40 } 41 42 43 public static void display(int a[]) 44 { 45 for(int i=0;i<a.length;i++) 46 System.out.println(a[i]); 47 } 48 49 50 86 }
时间: 2024-10-22 01:49:42