标签:sam 简单 数组下标 value map 快速 mil number one
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].
最直接的方式是采用暴力解法,tmp用来记录目标减去数组中一个数剩余的部分,然后再用tmp在数组中进行匹配。找到就返回。
这个方式的时间复杂度比较高,两次循环。具体方式如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0;i<nums.length;i++){
int temp = target - nums[i];
for(int j = 0;j<nums.length;j++){
if(i!=j&&temp == nums[j]){
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
我参考了solution中的其他方式,提到了用map来进行遍历,用空间换时间。利用map<k,v>的对应关系。可以快速定位,减少一次循环。
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");
}
在这个代码中,我陷入了一个误区,k用来存数组下标,value用来记录数组值,正确的方式正好相反,我们需要的是数组的下标,匹配的是数组值。
这一点要相当注意,我自己对于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");
}
这个方式是,先遍历后存储,遍历和存储同时进行,这种方式相对于前面两种方式是更加简单。
其实除了暴力解法以外,其余两种方式都利用了map的特性,这种思想值得我们学习。
利用一些数据结构降低代码的时间复杂度。时间与空间维持一个动态平衡。
标签:sam 简单 数组下标 value map 快速 mil number one
原文地址:http://www.cnblogs.com/liuchuan9504/p/7853763.html