zoukankan      html  css  js  c++  java
  • [LeetCode 217] Contians Duplicate

    Contains Duplicate I

    HashSet

    • add(): add an element into hashset, if it has the element return false, otherwise return true.

    Code

    public class Solution {
        public boolean containsDuplicate(int[] nums) {
            HashSet<Integer> hs = new HashSet<Integer>();
            for (int num: nums) {
                // if the set already contains the element, the add() will return false
                if (!hs.add(num)) {
                    return true;
                }
            }
            return false;
        }
    }
    

    Contains Duplicate II

    Explanation

    • use sliding window
    • keep a window with size k using HashSet
    • move forward one element, we deleted the last one and check if the window has an element as same as the new one.

    Code

    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
            HashSet<Integer> hs = new HashSet<Integer>();
            for (int i = 0; i < nums.length; i++) {
                if (!hs.add(nums[i])) {
                    return true;
                }
                if (i >= k) {
                    hs.remove(nums[i - k]);
                }
            }
            return false;
        }
    }
    

    Contains Duplicate III

    TreeSet

    • floor(num): return the greatest element less than or equal to num.
    • ceiling(num): return the least element greater than or equal to num.

    Explanation

    Code

    public class Solution {
        public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
            TreeSet<Integer> window = new TreeSet<Integer>();
            for (int i = 0; i < nums.length; i++) {
                Integer ceiling = window.ceiling(nums[i]);
                Integer floor = window.floor(nums[i]);
                if (ceiling != null && nums[i] >= ceiling - t) {
                    return true;
                if (floor != null && nums[i] <= floor + t) {
                    return true;
                window.add(nums[i]);
                if (i >= k) {
                    window.remove(nums[i - k]);
            }
            return false;
        }
    }
    
  • 相关阅读:
    Frameset 框架
    FHS 文件层次标准
    history 命令
    QT基础走起
    Android中导入jar包v4的错误
    Android工具Eclipse点击卡死或者无响应情况
    让程序飞起来
    Android中报错
    【2019.9.23】NOIP2017 practice exam
    【技巧】时间复杂度
  • 原文地址:https://www.cnblogs.com/Victor-Han/p/5178953.html
Copyright © 2011-2022 走看看