217. Contains Duplicate & 21

2017-04-13  本文已影响25人  Double_E

217. Contains Duplicate

https://leetcode.com/problems/contains-duplicate/#/description

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

超简单思路

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        if len(nums) <= 1:
            return False
        return len(set(nums)) != len(nums)

219. Contains Duplicate II

https://leetcode.com/problems/contains-duplicate-ii/#/description

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

分析

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        if len(set(nums)) == len(nums):
            return False
        d = {}
        for i in range(len(nums)):
            if nums[i] in d.keys() and i - d[nums[i]] <= k:
                return True
            else:
                d[nums[i]] = i
        return False    
        
        
上一篇下一篇

猜你喜欢

热点阅读