219 Contains Duplicate II 存在重復(fù)元素 II
Description:
Given an array of integers and an integer k, find out 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.
Example:
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
題目描述:
給定一個(gè)整數(shù)數(shù)組和一個(gè)整數(shù) k,判斷數(shù)組中是否存在兩個(gè)不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的絕對(duì)值最大為 k。
示例:
示例 1:
輸入: nums = [1,2,3,1], k = 3
輸出: true
示例 2:
輸入: nums = [1,0,1,1], k = 1
輸出: true
示例 3:
輸入: nums = [1,2,3,1,2,3], k = 2
輸出: false
思路:
利用 map記錄出現(xiàn)過(guò)的數(shù)字, 如果 map中已經(jīng)存放了這個(gè)數(shù)字, 要么滿足題意輸出 true, 要么更新下標(biāo)值
時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(k), map中最多記錄 k個(gè)元素
代碼:
C++:
class Solution
{
public:
bool containsNearbyDuplicate(vector<int>& nums, int k)
{
if (nums.size() < 2) return false;
map<int,int> temp;
for (int i = 0; i < nums.size(); i++)
{
if (temp.count(nums[i]))
{
if (i - temp[nums[i]] <= k) return true;
else temp[nums[i]] = i;
}
else temp[nums[i]] = i;
}
return false;
}
};
Java:
class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
if (nums.length < 2) return false;
Map<Integer, Integer> temp = new HashMap<>(k);
for (int i = 0; i < nums.length; i++) {
if (temp.containsKey(nums[i])) {
if (i - temp.get(nums[i]) <= k) return true;
else temp.put(nums[i], i);
} else {
temp.put(nums[i], i);
}
}
return false;
}
}
Python:
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
if len(nums) < 2:
return False
temp = {}
for i, num in enumerate(nums):
if num in temp:
if i - temp[num] <= k:
return True
else:
temp[num] = i
else:
temp[num] = i
return False