Contains Duplicate II

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 difference between i and j is at most k.

URL: https://leetcode.com/problems/contains-duplicate-ii/

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        if not nums:
            return False
        elif len(nums) == 1:
            return False
        elif len(nums) == 2:
            if nums[0] != nums[1]:
                return False
            else:
                if nums[0] == nums[1] and k >= 1:
                    return True
                else:
                    return False
        else:
            index_dict = {}
            for i in range(len(nums)):
                if nums[i] in index_dict:
                    prev_index = index_dict[nums[i]]
                    if i - prev_index <= k:
                        return True
                index_dict[nums[i]] = i
            return False

results matching ""

    No results matching ""