LeetCode 0001 -- 两数之和

mac2026-01-18  7

两数之和

题目描述

给定一个整数数组nums和一个目标值target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的 数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素(这里指元素下标不同,而不是指元素不同,如nums = [2, 5, 5, 15], target = 10,将返回[1, 2])。

示例:

给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]

解题思路

个人AC

借助HashMap数据结构将查询操作的时间复杂度从O(n)降到O(1):将遍历过的整数放进哈希表中。

import java.util.HashMap; class Solution { public int[] twoSum(int[] nums, int target) { if (null == nums || nums.length < 2) throw new IllegalArgumentException("Input array error"); HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[]{map.get(complement), i}; } map.put(nums[i], i); } throw new IllegalArgumentException("no tow sum solution"); } }

时间复杂度:O(n);

空间复杂度:O(n)。

最优解

同上。

最新回复(0)