问题描述

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.

代码

class Solution {
public:
	bool containsNearbyDuplicate(vector<int>& nums, int k) {
		map<int, int> m_map;
		for (int i = 0; i < nums.size(); i++) {
			if (m_map.find(nums[i]) != m_map.end()) {
				int pos = m_map[nums[i]];
				if (i - pos <= k) {
					return true;
				}
			}
			m_map[nums[i]] = i;
		}
		return false;
	}
};