LeetCode 219. Contains Duplicate II
原题链接在这里:https://leetcode.com/problems/contains-duplicate-ii/
题目:
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.
题解:
是Contains Duplicate的进阶版题目,类似题目还有Contains Duplicate III.
建立一个HashMap hm, key是nums[i], value 是 index i.
对于nums[i], 检查它时候在 hm中,若不在,就加<nums[i], i>进去.
若是nums[i] 在 hm 中,就要看当前的i 和 hm中对应nums[i]的 value 的差值是否比k大:
若是比k 大,说明不符合条件,去掉旧的pair,添加当前pair.
若是不比k大,则return true.
这里熟练几个 HashMap functions: hm.put(key, value); hm.get(key); hm,remove(key): hm.containsKey(key).
Time Complexity: O(n). Space: O(n).
AC Java:
1 public class Solution { 2 public boolean containsNearbyDuplicate(int[] nums, int k) { 3 if(nums == null || nums.length == 0){ 4 return false; 5 } 6 HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); 7 for(int i = 0; i<nums.length; i++){ 8 if(!hm.containsKey(nums[i])){ 9 hm.put(nums[i],i); 10 }else if(i - hm.get(nums[i]) > k){ 11 hm.put(nums[i], i); 12 }else{ 13 return true; 14 } 15 } 16 return false; 17 } 18 }
AC C++:
1 class Solution { 2 public: 3 bool containsNearbyDuplicate(vector<int>& nums, int k) { 4 unordered_map<int, int> map; 5 for(int i = 0; i < nums.size(); i++){ 6 if(map.find(nums[i]) != map.end() && i - map[nums[i]] <= k){ 7 return true; 8 } 9 10 map[nums[i]] = i; 11 } 12 13 return false; 14 } 15 };