5/25 每日一題(重複的值,並且索引差小於k)
Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false
Constraints:
1 <= nums.length <= 105-109 <= nums[i] <= 1090 <= k <= 105
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
nums_dict={} #使用這個字典紀錄重複的值和索引
for n,i in enumerate(nums):
if i in nums_dict and n - nums_dict[i] <= k:
#如果符合 重複的值 且 索引值差小於等於k 回傳True
return True
nums_dict[i]=n #加入字典
return False
標籤: leetcode

0 個意見:
張貼留言
訂閱 張貼留言 [Atom]
<< 首頁