1. 程式人生 > >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; } };