【力扣热题100】哈希——两数之和
题目
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那两个整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案,并且你不能使用两次相同的元素。
你可以按任意顺序返回答案。
链接:https://leetcode.cn/problems/two-sum/description/?envType=study-plan-v2&envId=top-100-liked
思路
思路一
暴力,两次循环。枚举数组中的每一个数 x
,寻找数组中是否存在 target - x
。时间复杂度O(n²)
思路二
在思路一的基础上,对已经枚举过的数字进行记录,放于Map中。从而可以减少一次遍历。时间复杂度O(n)
题解
public int[] twoSum(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<>();int[] result = new int[2];for (int i = 0; i < nums.length; i++) {int complement = target - nums[i];if (map.containsKey(complement)) {result[0] = map.get(complement);result[1] = i;return result;} else {map.put(nums[i], i);}}return result;}