题目:
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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
其实就是从数组里找到两个数,其和为target。注意返回结果是索引而不是数值。
思路一:嵌套循环,毫无疑问,这是最容易被想到的最直接的思路了。没什么好解释的,直接上代码。但是由于嵌套循环,所以时间复杂度很高。
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
int [] res = new int[2];
for(int i=0; i<n-1; i++)
{
for(int j=i+1; j<n; j++)
{
if(nums[i]+nums[j] == target)
{
res[0] = i;
res[1] = j;
return res;
}
}
}
return res;
}
思路二:使用HashMap数据结构,用来保存已经读取过的数及其索引。牺牲空间复杂度换取时间复杂度。O(N)。
public 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;
}
思路三:将数组进行排序,然后使用两个游标指针进行判断。这里需要注意的是在数组进行排序时会使其下标索引发生变化,所以此处使用一个转换技巧,将原数组进行重新编码:
nums[i] = nums[i] * n + (nums[i] < 0 ? -i : i);
这样做使得新的数组即包含了其索引值,排序也不会发生变化。可以很好的解决我们的问题。
如:【3,2,-7,9】—》【12,10,-35,45】
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for(int i = 0; i < n; i++)
nums[i] = nums[i] * n + (nums[i] < 0 ? -i : i);
Arrays.sort(nums);
int lo = 0, hi = n - 1;
while (lo < hi) {
int sum = nums[lo]/n + nums[hi]/n;
if (sum == target) return new int[]{nums[lo] < 0 ? -nums[lo] % n : nums[lo] % n, nums[hi] < 0 ? -nums[hi] % n : nums[hi] % n};
if (sum < target) lo++;
else hi--;
}
throw new IllegalArgumentException();
}
以上三种思路耗时越来越短,尤其是方法三使用了编码的思路使得数组排序变为可行方案,大大减少了程序用时。