Contains Duplicate II

来源:互联网 发布:金十数据看白银 编辑:程序博客网 时间:2024/06/06 04:56

题目地址:https://leetcode.com/problems/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 difference between i and j is at most k.

Contains Duplicate 类似,用HashMap就能解决这个问题,无非是这次要存储元素的位置信息了。

步骤如下:

  1. 如果一个元素在map中不存在,那么推进去;
  2. 如果存在,那么比较一下当前元素与以前元素的位置差有多少,小于等于k,返回true,否则继续循环,注意:这里要更新该元素的在map中的位置信息了,因为前面的位置已经超过k了,但是不等于后面就再没有这样的元素了,比如{1,0,1,1}与1。

代码实现如下:

public class ContainsDuplicateII {    public static boolean containsNearbyDuplicate(int[] nums, int k) {        HashMap<Integer, Integer> map = new HashMap<>();        for (int i = 0; i < nums.length; i++) {            if (map.containsKey(nums[i])){                if (i - map.get(nums[i]) <= k)                    return true;                else {                    map.put(nums[i], i);                    continue;                }            }else {                map.put(nums[i], i);            }        }        return false;    }    public static void main(String[] args) {        int[] a = {1,0,1,1};        int k = 1;        System.out.println(containsNearbyDuplicate(a, k));    }}
0 0