题目描述:给定一个列表,返回一个数组中两个数相加为target的下标索引。
题目链接:Leetcode 1. Two Sum
开始我的思路是先排序,然后双指针向中间移动,然后记录此时的值,再到原数组去寻找对应值下标注意处理相同值的情况。
正确的思路就是利用hashmap来记target-nums[idx]
当出现的数在哈希表内时,证明已经找到了结果了。
一般数组的题目都是用哈希表空间换时间的思想来得出结果,或者维护队列、维护单调栈、维护滑动窗口、维护插入顺序的哈希表接可以得出结果了。
代码如下
import java.util.Arrays;
import java.util.HashMap;
class Solution {
public int[] twoSum(int[] nums, int target) {
if (nums.length < 2){
return null;
}
int[] ans = new int[2];
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(nums.length);
for (int idx = 0; idx < nums.length; idx++) {
int res = target - nums[idx]; //下一个要寻找的值
if (hm.containsKey(nums[idx])==true) { //证明这个idx和hm存储的idx就是答案
ans[0] = hm.get(nums[idx]);;
ans[1] = idx;
} else {
hm.put(res, idx);
}
}
return ans;
}
}
#第一次的做法
import java.util.Arrays;
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] ans = new int[2];
int[] numNew = new int[nums.length];
System.arraycopy(nums, 0, numNew, 0, nums.length);
Arrays.sort(numNew);
int l = 0;
int r = nums.length - 1;
int currSum;
while (l < r) {
currSum = numNew[l] + numNew[r];
if (currSum < target) {
l++;
} else if (currSum > target) {
r--;
} else {
boolean flag = true;
for (int i = 0; i < nums.length; i++) {
if ((nums[i] == numNew[l] || nums[i] == numNew[r]) && flag==true) {
ans[0] = i; //左边index
flag = false;
} else if ((nums[i] == numNew[r] || nums[i] == numNew[l]) && flag==false) {
ans[1] = i; // 右边
}
}
return ans;
}
}
return null;
}
}