本文共 758 字,大约阅读时间需要 2 分钟。
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.
此题在上一题Contains Duplicate的基础上,要求重复元素的半径不大于K。上题中,map中元素值为Key,元素索引下表为Value。所以在找到重复的情况下,可以判断下标差是否小于等于K。如果大于K,则修改已在map中元素对应的value,即下标。
class Solution {public: bool containsNearbyDuplicate(vector & nums, int k) { mapint_map; map ::iterator iter; for (int i = 0; i second <= k) { return true; }else{ int_map.erase(iter); } } int_map.insert(pair (nums[i], i)); } return false; }};
转载地址:http://rfxti.baihongyu.com/