bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_map<int, list<size_t>> numIndexListDic; for (size_t i = 0; i < nums.size(); ++i){ auto loc = numIndexListDic.find(nums[i]); if (loc == numIndexListDic.end()){ numIndexListDic[nums[i]] = list<size_t>{i}; } else{ auto nearbyDuplicateIt = find_if(loc->second.cbegin(), loc->second.cend(), [&](size_t index){return i - index <= k;}); if (nearbyDuplicateIt != loc->second.cend()){ return true; } loc->second.push_back(i); } } return false; }
时间: 2024-10-13 11:31:26