Leetcode 220 Contains Duplicate III Solution in java | Hindi Coding Community

0

 


You are given an integer array nums and two integers indexDiff and valueDiff.

Find a pair of indices (i, j) such that:

i != j,

abs(i - j) <= indexDiff.

abs(nums[i] - nums[j]) <= valueDiff, and

Return true if such pair exists or false otherwise.



Example 1:


Input: nums = [1,2,3,1], indexDiff = 3, valueDiff = 0

Output: true



class Solution {
    public boolean containsNearbyAlmostDuplicate(int[] nums, int indexDiff, int valueDiff) {
        TreeSet<Long> set = new TreeSet<>();

        for (int i = 0; i < nums.length; i++) {

            Long num = new Long(nums[i]);
            Long floor = set.floor(num);
            Long ceil = set.ceiling(num);

            if (floor != null && Math.abs(floor - num) <= valueDiff) {
                return true;
            }

            if (ceil != null && Math.abs(ceil - num) <= valueDiff) {
                return true;
            }

            set.add(num);

            if (set.size() > indexDiff) {
                set.remove(1L * nums[i - indexDiff]);
            }
        }

        return false;
    }
}

// TC: O(n * logk), SC: O(k)

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !