LeetCode: 219. Contains Duplicate II

LeetCode: 219. Contains Duplicate II

题目描述

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 betweeni and j is at most k.

Example 1:

Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1
Output: true

Example 3:

Input: nums = [1,2,3,1,2,3], k = 2
Output: false

解题思路

依次遍历数组,用 map 记录当前数字的最近出现的位置,当位置差小于 k 时返回 true

AC 代码

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        map<int, int> num2Idx;
        bool bRet = false;
        
        for(int i = 0; i < nums.size(); ++i)
        {
            if(num2Idx.find(nums[i]) == num2Idx.end() || i - num2Idx[nums[i]] > k)
            {
                num2Idx[nums[i]] = i;
            }
            else
            {
                bRet = true;
                break;
            }
        }
        
        return bRet;
    }
};
全部评论

相关推荐

04-25 18:13
五邑大学 Java
后来123321:大二两段实习太厉害了,我现在大二连面试都没有
点赞 评论 收藏
分享
03-30 19:30
石家庄学院 Java
野蛮的柯基在游泳:都能入股了,还得是Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务