[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;
    }
}

转载于:https://www.cnblogs.com/Victor-Han/p/5178953.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值