LeetCode 1-两数之和

mac2025-11-16  3

LeetCode 1-两数之和

语言:python 思路:字典,key : value=目标整数-数组中某项 : 数组中该项索引 好处是查找时间复杂度O(1),空间消耗大一些

class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ dic={} for i in range(len(nums)): dic[target-nums[i]]=i for j in range(len(nums)): if nums[j] in dic and j!=dic[nums[j]]: ''' 依题意“不能重复使用数组内元素” 此处如果不加入and之后的语句,会出现逻辑漏洞, 对于输入nums=[3,2,4],target=6,会返回[0,0]而非[2,4] ''' return j,dic[nums[j]]
最新回复(0)