本文主要是介绍Leetcode36: Contains Duplicate II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Given an array of integers and an integer k, find out whether there there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between iand j is at most k.
题目意思是:在一个数组里找到两个相同的数,并且他们的索引值之差不超过k,那么返回true。
可以建立一个map映射,存放不重复的数值和对应的索引。
class Solution {
public:bool containsNearbyDuplicate(vector<int>& nums, int k) {map<int, int> dup;for(int i = 0; i < nums.size(); i++){if(dup.find(nums[i]) != dup.end() && i - dup[nums[i]] <= k){return true;}else{dup[nums[i]] = i;}}return false;}
};
这篇关于Leetcode36: Contains Duplicate II的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!