zoukankan      html  css  js  c++  java
  • leetcode 219. Contains Duplicate II 求一个数组中有没有重复元素 ---------- java

    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.

    与217类似,就是多加了一个要求i和j距离最远是k。
     
    1、HashMap最直接。
    public class Solution {
        public 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;
                    }
                } 
                map.put(nums[i], i);
            }
            return false;
        }
    }
     2、用HashSet也可以,用窗口的想法来实现。
    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            HashSet<Integer> set = new HashSet();
            for (int i = 0; i <= k && i < nums.length; i++){
                if (set.contains(nums[i])){
                    return true;
                }
                set.add(nums[i]);
            }
            for (int i = k + 1, j = 0; i < nums.length; i++, j++){
                set.remove(nums[j]);
                if (set.contains(nums[i])){
                    return true;
                }
                set.add(nums[i]);
            }
            return false;
        }
    }

    可以对上面的代码简化一下。

  • 相关阅读:
    UE4项目《和平精英》渲染技术浅析
    如何用CMake构建Android C++库
    Unity Native Plugin
    多边形三角化
    参考图
    Unity SRP学习笔记
    Macbook Pro HDMI 无信号解决办法
    CGAL计算几何算法库
    无标记动作捕捉
    PS 鼠绘
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6734983.html
Copyright © 2011-2022 走看看