LeetCode第一题:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
开始想了个很笨的方法:
- 先对数组进行一个排序
- 使用双指针,一个指向头less,一个指向尾more
- 两个指针位置上的数相加
- 如果小于target,那么less++
- 如果小于target,那么more–
- 如果相等,则找到了两个对应的值
class Solution {
public int[] twoSum(int[] nums, int target) {
int num[] = new int[nums.length];
for(int i = 0;i < nums.length;i++){
num[i] = nums[i];
}
Arrays.sort(nums);
int[] arr = new int[2];
int less = 0;
int more = nums.length - 1;
while(less < more){
if(nums[less] + nums[more] < target){
less++;
} else if(nums[less] + nums[more] > target){
more--;
} else {
arr[0] = nums[less];
arr[1] = nums[more];
break;
}
}
for(int i =0;i < num.length;i++){
if(num[i] == arr[0]){
arr[0] = i;
break;
}
}
for(int i = num.length - 1;i >= 0;i--){
if(num[i] == arr[1]){
arr[1] = i;
break;
}
}
return arr;
}
}
然后看了下官方的解答,感觉自己好笨,太菜了
- 使用HashMap,值作为key,对应的下标作为value
- 遍历扫描数组,将数组的值存入Map当中
- 用target减去数组上的数,得出一个差值
- 检查这个差值是否存在于HashMap当中
- 如果存在,则找到了相对应的两个值的下标
- 如果不存在,则继续;遍历完都没有,则表明不存在这么两个数
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap();
for(int i = 0;i < nums.length;i++){
int key = target - nums[i];
if(map.containsKey(key)){
return new int[]{i,map.get(key)};
}else{
map.put(nums[i],i);
}
}
throw new IllegalArgumentException("No two sum solution");
}
}