1. 两重循环
o N^2
java
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
int[] res = new int[2];
for(int i=0;i<n;i++){
for(int j =0;j<n;j++){
if( i != j && nums[i]+ nums[j] == target){
return new int[]{i,j};
}
}
}
return res;
}
}
2. HashMap
- 放入HaspMap
- 从中是否有合适的
java
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
int[] res = new int[2];
Map<Integer, Integer> map = new HashMap<>();
for(int i=0;i<n;i++){
map.put(nums[i], i);
}
for(int i=0;i<n;i++){
Integer j = map.get(target - nums[i]);
if(j != null && i!=j){
res[0] = i;
res[1] = j;
return res;
}
}
return res;
}
}
3. 官解2,确实比我自己想的要精妙
把i当作第二个因子,如果存在解,那么第一个因子肯定已经放入map中了。所以可以大胆的一遍查找,一边填充元素
java
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
Map<Integer, Integer> map = new HashMap<>();
for(int i=0;i<n;i++){
int j = target - nums[i];
if(map.containsKey(j)){
return new int[]{i, map.get(j)};
}
map.put(nums[i], i);
}
return new int[0];
}
}