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 between i 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

难度:easy

题目:给定一整数数组和一整数K,找出是否存在两个不同的下标使用得nums[i]=nums[j]并且i与j之差的绝对值小于等于k.

思路:hashmap

Runtime: 9 ms, faster than 81.45% of Java online submissions for Contains Duplicate II.
Memory Usage: 41 MB, less than 77.21% of Java online submissions for Contains Duplicate II.

public class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Map<Integer, Integer> mii = new HashMap<>();
        
        for (int i = 0; i < nums.length; i++) {
            if (mii.containsKey(nums[i]) && i - mii.get(nums[i]) <= k) {
                return true;
            }
            mii.put(nums[i], i);
        }
        
        return false;
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018231874
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞