No1.
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
个人LOW B代码:
public static int[] twoSum(int[] numbers, int target){
int []arr=new int[2];
for(int i=0;i<numbers.length;i++){
for(int j=numbers.length-1;j>=0;j--){
if(numbers[i]+numbers[j]==target){
arr[0]=i;
arr[1]=j;
return arr;
}
}
}
return arr;
}
较好代码:
public static int[] twoSum(int[] numbers, int target) {
int[] result = new int[2];
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; i++) {
if (map.containsKey(target - numbers[i])) {
result[1] = i;
result[0] = map.get(target - numbers[i]);
return result;
}
map.put(numbers[i], i);
}
return result;
}
较好代码简化版:
public int[] twoSum(int[] numbers, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < numbers.length; map.put(numbers[i], i))
if (map.containsKey(target - numbers[i]))
return new int[]{map.get(target - numbers[i]),i};
return new int[]{0,0};
}
}
No1 总结:个人代码,是从第一个数组元素开始查起 直到查不到,而较好代码是查询相距最近且总和为target的结果,且后者时间复杂度为O(n)==》仅限于JAVA中,C++可能是lgn, 较好代码有个bug,就是数组中有相同元素,因为map的缘故,所以排列在后面的元素会覆盖前面的元素来作为key存放到
map中,所以显示会出现同一个位置 如[3,3,2,4] 输出为1,1
原文:http://www.cnblogs.com/KingIceMou/p/7468672.html