首页 > 其他 > 详细

1319. 包含重复值 II

时间:2020-04-20 09:50:20      阅读:66      评论:0      收藏:0      [点我收藏+]

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未通过,异常,时间复杂度问题,待优化。

 

1319. 包含重复值 II

原文:https://www.cnblogs.com/yunxintryyoubest/p/12735437.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!