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;
        }
    }
  • 相关阅读:
    201215-03-19---cocos2dx内存管理--具体解释
    sqlHelper的增删改查
    Java Web的数据库操作(一)
    Myeclipse 中添加mysql的jdbc驱动
    MySQL索引的创建、删除和查看
    搭建Windows下Java Web开发环境
    Qt 格式化字符串
    实现C++模板类头文件和实现文件分离的方法
    Qt Creator实现状态栏显示
    Win7 64位下配置Qt5.3和Wincap
  • 原文地址:https://www.cnblogs.com/kevincong/p/7900358.html
Copyright © 2011-2022 走看看