最简单的就是写两个循环,但写两个循环的时间复杂度o(n^2)太差了,一般不会是个很好的算法。
public int[] twoSum(int[] numbers, int target){ int[] res = new int[2]; for(int i = 0;i<numbers.length;i++){ for(int j=i+1;j<numbers.length;j++){ if(number[i]+numbers[j] == target){ res[0] = i+1; res[1] = j+1; return res; } } return null; } }
别人的代码:
public int[] twoSum(int[] numbers, int target){ int[] res = new int[2]; if(numbers == null || numbers.length < 2) return null; HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i = 0;i<numbers.length;i++){ if(map.containsKey(target-numbers[i])){ res[0] = map.containKeys(target-numbers[i]); res[1] = i; return res; } map.put(numbers[i],i); } return null; }
原文:http://www.cnblogs.com/heylinart/p/7653388.html