Contains Duplicate II

来源:互联网 发布:c语言鸡兔同笼代码 编辑:程序博客网 时间:2024/06/05 05:01

题目:

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

解法:

class Solution:
    # @param {integer[]} nums
    # @param {integer} k
    # @return {boolean}
    def containsNearbyDuplicate(self, nums, k):
        sorted_nums = nums[:]
        sorted_nums.sort()
        if len(nums)<=1:
            return False
        for index,value in enumerate(sorted_nums):
            if index<len(sorted_nums)-1 and value==sorted_nums[index+1]:
                index1 = nums.index(value)
                nums.remove(value)
                index2 = nums.index(value)+1
                if index2-index1<=k:
                    return True
        return False
        

0 0
原创粉丝点击