1. Two SumGiven 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.
翻译:给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。
基础解法 O(n^2)
public int[] twoSum(int[] nums, int target) {
int[] dd = new int[2];
for (int i = 0; i < nums.length; i++) {
int dec = target - nums[i];
for (int j = 1; j < nums.length; j++) {
if (dec == nums[j] && i != j) {
dd[0] = i;
dd[1] = j;
return dd;
}
}
}
return dd;
}
- 两个for循环,这种方法最坏情景是最后两位相加=target,只看内循环,第一位到第最后一位分别访问了....(n-1) 次,复杂度达到了O(n^2),速度不尽人意
进阶解法 O(lgn)
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int result[] = new int[2];
for (int i = 0; i < nums.length; i++){
int num = target - nums[i];
if(map.containsKey(num)){
result[0] = map.get(num);
result[1] = i;
return result;
}
map.put(nums[i], i);
}
return result;
}
JDK1.7的hashmap 极端情况下,可能只有单个链表,效率依然不高,1.8加入了红黑树,最差情况下高度不超过最低高度的2倍