1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | /** * @brief 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. * * example1: * input :nums[1,2,3,1],k=3 * Output:true * * example2: * input:nums[1,0,1,1],k=1 * output:true * * example3: * Input:nums[1,2,3,1,2,3],k=2 * output:false */ class Solution{ public : bool containsNearbyDuplicate(vector< int >& nums, int k){ unordered_map< int , int > m; for ( int i = 0; i < nums.size(); i++){ int n = nums[i]; if (m.find(n) != m.end() && i - m[n] <=k){ return true ; } m[n] = i; } return false ; } }; |
怕什么真理无穷,进一寸有一寸的欢喜。---胡适
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步