1319. 包含重复值 II

1319. 包含重复值 II

中文 English

给定一个整数的数组和一个整数k,找出数组中是否有两个不同的索引ij,使得nums [i] = nums [j]并且ij之间的差值的绝对值最多为k

样例

样例 1:

输入:nums = [1,2,1], k = 0
输出:False

样例 2:

输入:nums = [1,2,1], k = 2
输出:True
解析:nums[0] = nums[2] 并且 2 - 0 <= 2
class Solution:
    """
    @param nums: the given array
    @param k: the given number
    @return:  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
    """
    '''
    大致思路:
    1.循环进行切割,判断是否存在重复的值,如果存在,直接返回True,否则返回False,给出一个方法。
    '''
    def containsNearbyDuplicate(self,nums,k):
        for i in range(len(nums)-k):
            if self.isSameList(nums[i:i+k+1]) == True:
                return True
        return False
            

    def isSameList(self,l):
        dic = {}
        for i in l:
            dic[i] = dic.get(i,0)+1
        
        for k,v in dic.items():
            if v > 1:
                return True
        return False

注:lintcode未通过,异常,时间复杂度问题,待优化。

 

猜你喜欢

转载自www.cnblogs.com/yunxintryyoubest/p/12735437.html
ii