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;
        }
    }
    
  • 相关阅读:
    数据的图表统计highcharts
    spring文件的上传和下载
    项目随笔@Service("testService")-------第二篇
    spring的四种数据源配置
    spring之interceptor篇
    spring过滤器篇
    SecurityManager篇
    Apache shiro篇
    日期工具方法
    定时器CronExpression配置说明详解
  • 原文地址:https://www.cnblogs.com/Victor-Han/p/5178953.html
Copyright © 2011-2022 走看看