标签:nlog find dice integer contain most ice lock NPU
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.
Input: nums = [1,2,3,1], k = 3, t = 0
Output: true
Input: nums = [1,0,1,1], k = 1, t = 2
Output: true
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: true
先给一个暴力解法,复杂度\(O(N*K)\),使用滑动窗口来求解。还能优化成\(O(NlogN)\)
class Solution:
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
if len(nums) < 2 or k < 1 or t < 0:
return False
if t == 0 and len(set(nums)) == len(nums):
return False
for i in range(len(nums) - 1):
# 窗口的长度为k,但不能超过数组nums的长度
for j in range(i + 1, min(len(nums), i + k + 1)):
if abs(nums[i] - nums[j]) <= t:
return True
return False
Leetcode 220. 存在重复元素 III (Contains Duplicate III)
标签:nlog find dice integer contain most ice lock NPU
原文地址:https://www.cnblogs.com/yufeng97/p/12602295.html