Skip to content
Branch: master
Find file History
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.

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 i and j is at most k.


使用hashmap,key存储值,value存储索引, 若nums[i]在hashmap中,则若i - map[nums[i]] <= k, 返回true

bool containsNearbyDuplicate(vector<int> &nums, int k) {
	unordered_map<int, int> map;
	int n = nums.size();
	for (int i = 0; i < n; ++i) {
		if (map.find(nums[i]) != map.end()) {
			int s = map[nums[i]];
			if (i - s <= k)
				return true;
		map[nums[i]] = i;
	return false;


You can’t perform that action at this time.