48ms easy to understand python solution

  • 0
    class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        :type nums: List[int]
        :type k: int
        :rtype: bool
        if len(nums) == len(set(nums)):  #check if there is duplicates
            return False
        dis = []
        for i in xrange(len(nums)):
            if i != len(nums) - 1 -nums[::-1].index(nums[i]):
                dis.append([kk for kk, x in enumerate(nums) if x == nums[i] ])  #get all indices of duplicate numbers
        for i in xrange(len(dis)):
            for j in xrange(1,len(dis[i])):
                if dis[i][j] - dis[i][j-1] <= k:          
                    return True
        return False

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.