• 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;
        }
    }
  • 相关阅读:
    我与solr(二)--导入mysql数据库
    Android 渐变效果
    希尔排序
    插入排序
    选择排序
    冒泡排序法
    QT仿QQ页面
    Colliding Mice
    QTablewidget通过代理实现限制输入
    QT绘制心形图案二
  • 原文地址:https://www.cnblogs.com/kevincong/p/7900358.html
Copyright © 2020-2023  润新知