[leetcode] 220. Contains Duplicate III @ python

版权声明:版权归个人所有,未经博主允许,禁止转载 https://blog.csdn.net/danspace1/article/details/88657116

原题

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

Example 1:

Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Example 2:

Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Example 3:

Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false
Accepted
87,182
Submissions
447,414

解法

暴力解法. 遍历nums, 然后找i+k以内的数, 如果两个数的差的绝对值<= t, 返回True. Base case是当t= 0且nums没有重复值时, 返回False.

代码

class Solution(object):
    def containsNearbyAlmostDuplicate(self, nums, k, t):
        """
        :type nums: List[int]
        :type k: int
        :type t: int
        :rtype: bool
        """
        l = len(nums)
        if t == 0 and l == len(set(nums)):            
            return False
        
        for i in range(l):
            for j in range(i+1, i+k+1):
                if j < l and abs(nums[i] - nums[j]) <= t:
                    return True
        return False

猜你喜欢

转载自blog.csdn.net/danspace1/article/details/88657116