letecode [219] - 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.
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
题目大意:
给定数组,判断数组中是否存在nums[i]=nums[j],即重复的元素,要求下标i,j的绝对值差最小。
理 解:
用map保存元素和最近出现的下标,若当前元素在map中,则比较两元素下标差,更新difMax为最小的差。
difMax <= k 则满足条件。否则返回false.
代 码 C++:
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { map<int,int> m; map<int,int>::iterator it; int difMax = INT_MAX; for(int i=0;i<nums.size();++i){ it = m.find(nums[i]); if(it == m.end()){ m.insert(pair<int,int>(nums[i],i)); }else{ if(i - (it->second) < difMax){ //cout<<it->second; difMax = i - (it->second); it->second = i; } } } if(difMax>k) return false; else return true; } };
运行结果:
执行用时 :88 ms, 在所有C++提交中击败了17.53%的用户
内存消耗 :15.4 MB, 在所有C++提交中击败了7.28%的用户