Skip to content

Latest commit

 

History

History
 
 

ContainsDuplicateII

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

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.

Solution

使用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;
}

扩展