1. Two Sum
Easy
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].
解法1:排序+两头夹击
题中没说所给数组一定是有序的,所以我们假设数组是非有序的。
1. 对数组从小到大排序,可用快排算法
2. 数组开头结尾各设一指针即为 l 和 r
3. 将l和r所指向的数值相加得到sum,并与target做对比
4. 如果sum > target,说明r所指向的数值过大,所以r左移一步;继续循环;
如果sum < target,说明l所指向的数值过小,所以需要右移一步;继续循环;
如果sum == target,说明已经找到了能够凑成target的两个数值;停止循环
5. 至此,我们虽然虽然找到了这两个数值,但是因为之前对数值重排序过了,所以现在的数值所在索引位置未必是之前原数组的。因此我们需要对原数组遍历,找到这两个数值对应的索引。这个操作用一次循环即可。
public static int[] twoSum(int[] nums, int target) {
int[] copy = Arrays.copyOfRange(nums, 0, nums.length);
Arrays.sort(nums);
int left = 0;
int right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum < target) {
left++;
} else if (sum > target) {
right--;
} else {
break;
}
}
int l = -1, r = -1;
for (int i = 0; i < copy.length; i++) {
if (copy[i] == nums[left] && l == -1) {
l = i;
} else if (copy[i] == nums[right]) {
r = i;
}
}
return new int[] { l, r };
}
解法2:HashMap记录索引位
因为题中明确说了仅有两个数字相加可组成target。说明如果真的存在这两个数,那么只要数组中存在其中一个数,那么另一个数就必定存在在数组中剩下的几个数中。所以我们可以通过一个hashmap记录每个数值在数组中的索引位置。Key为数值本身,value为索引位。这样我们可以依次遍历数组中的值,并假设当前值为组成target的其中一个值,然后判断map中是否存在另一个数(target-当前值);如果存在,那么返回map中相应的key对应的value即可。
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}
解法3:HashMap记录索引位(优化版)
根据解法2,其实无需一开始就遍历一次数组将数字依次存入map。我们可以在遍历判断的同时去初始化map。理由是如果target=a+b,那么及时在遍历a的时候b还没有被存入map中,那么在遍历到b的时候a也必然会在此之前被存入了map。
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[] { map.get(complement), i };
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No two sum solution");
}