有一题不会,请各位专家解答!
有一题不会,请各位专家解答!
有一题不会,请各位专家解答!

关注让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言问题描述: 给定一个整数数组nums和一个目标值target,在该数组中找出和为目标值的那两个整数,并返回它们的数组下标,假设每种输入只会对应一个答案,且同样的元素不能被重复利用。 示例: 给定nums = [2,7,11,15],target = 9 因为nums [ 0 ] + nums [ 1 ] = 2 + 7 = 9, 返回[ 0,1 ] 。 回答: 解题思路: 利用哈希表的思想,存储遍历的元素和它对应下标的映射关系,对于每一个遍历到的元素,我们都首先查询哈希表中是否存在满足目标和的另一个元素,如果存在,则直接返回两个元素的下标即可;如果不存在,则将当前元素和它的下标存入哈希表中,继续往下遍历数组。 代码实现: Python class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
hashmap = {}
for i, num in enumerate(nums):
if target - num in hashmap:
return [hashmap[target - num], i]
hashmap[num] = i
Java class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> hashmap = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (hashmap.containsKey(complement)) { return new int[] {hashmap.get(complement), i}; } hashmap.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution"); } } C++ class Solution { public: vector twoSum(vector& nums, int target) { unordered_map<int, int> hashmap; for (int i = 0; i < nums.size(); i++) { int complement = target - nums[i]; if (hashmap.count(complement)) { return vector{hashmap[complement], i}; } hashmap[nums[i]] = i; } throw invalid_argument("No two sum solution"); } }; 时间复杂度:$O(n)$