zoukankan      html  css  js  c++  java
  • leetCode-Contains Duplicate II

    Decsription:
    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.

    My Solution:

    class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            Map<Integer,List> indexMap = new<Integer,List> HashMap();
            int len = nums.length;
            for(int i = 0;i < len;i++){
                List<Integer> list;
                if(indexMap.get(nums[i]) == null){
                    list = new ArrayList<Integer>();
                    list.add(i);
                    indexMap.put(nums[i],list);
                }else{
                    list = (ArrayList<Integer>)indexMap.get(nums[i]);
                    list.add(i);
                }
                if(list.size() >= 2){
                    if(list.get(list.size() - 1) - list.get(list.size() - 2) <= k){
                        return true;
                    }
                }
            }
            return false;
        }
    }

    Better Solution:

    //set相当于缓存k+1个不相等的元素,一旦个数超过k+1个,那么每次都会清除掉"队首"元素(set无序,形象化理解是这样,其实是通过nums[i - k + 1]实现的)。因此,如果一个元素加入set,
    !set.add()返回true,则说明有两个元素相等且diff<=k;
    class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            Set<Integer> set = new HashSet<>();
            for (int i = 0; i < nums.length; i++) {
                if (i > k) {
                    set.remove(nums[i - k - 1]);
                }
                set.add(),如果set包含nums[i],那么返回false,如果不包含,返回true
                if (!set.add(nums[i])) {
                    return true;
                }
            }
            return false;
        }
    }

    Best Solution:

    class Solution {
    //通过map保存元素下标
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            if(k > 3000) return false;
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            for(int i = 0; i < nums.length; i++) {
                if (map.containsKey(nums[i]) && (i - map.get(nums[i]) <= k)) {
                    return true;
                } else {
                    map.put(nums[i], i);
                }
            }
            return false;
        }
    }
  • 相关阅读:
    selenium浏览器参数设置详解——转
    py打包工具
    BurpSuite暴力破解和防御实战
    费马小定理(确定n 是否为素数)
    如何实现一个RPC框架1 —— RPC简介和通信协议的定义
    如何实现一个RPC框架2 ——用Netty实现协议通信
    15.三数之和
    flex开发零碎笔记,随时补充
    转“国内图片网站Yupoo的架构”
    转“经验分享:大型高并发高负载网站的系统架构 ”
  • 原文地址:https://www.cnblogs.com/kevincong/p/7900358.html
Copyright © 2011-2022 走看看