1. 两数之和
输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。 1.解题思路:首先两层循环遍历可直接得出答案。 如何降低复杂度? 可以借助hashmap来完成,记录值和下表的功能
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> res = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (res.containsKey(target - nums[i])) {
return new int[]{res.get(target - nums[i]), i};
}
//记录值和下标
res.put(nums[i], i);
}
return nums;
}
}