1319. Contains duplicate value II

1319. Contains duplicate value II

Chinese English

Given an integer a 数组and an integer k, to find out if there are two different indexes in the array iand jso that nums [i] = nums [j]and iand jthe absolute value of the difference between the maximum k.

Sample

Example 1:

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

Sample 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
     "" "
     '' '
     General idea:
     1. loop Perform cutting to determine whether there are duplicate values. If it exists, return True directly, otherwise return False, and give a method.
     '' '
     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

Note: lintcode failed, abnormal, time complexity issues, to be optimized.

 

Guess you like

Origin www.cnblogs.com/yunxintryyoubest/p/12735437.html