python leetcode刷题归纳

语言:python
多想多做,坚持!!!你会越来越棒的!!!
1 Two Sum
167 Two Sum II - Input array is sorted
217 Contains Duplicate
219 Contains Duplicate II
这四道题目思路类似,均可以通过在遍历列表的时候使用enumerate函数将list变为dict来解,其中key为列表元素,value为对应元素的索引值
solution1

class Solution:
    def twoSum(self, nums, target): 
        # hhsolution:
        tmpdict = {}
        for i,nums in enumerate(nums):
            if (target-nums) in tmpdict:
                return [tmpdict[target-nums],i]
            tmpdict[nums] = i

solution167

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        # hhsolution:
        record = {}
        for i,num in enumerate(numbers):
            if (target-num) in record:
                return [record[target-num]+1,i+1]
            record[num] = i    

solution217

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
		# hhsolution:
        record = {}
        for i,nums in enumerate(nums):
            if nums in record:
                return True
            record[nums] = i
        return False

solution 219

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        # hhsolution:
        record = {}
        for i,num in enumerate(nums):
            if num in record and i-record[num]<=k:
                return True
            record[num] = i
        return False

你可能感兴趣的:(language)