Contains Duplicate III

Given an array of integers, find out whether there are two distinct indicesiandjin the array such that theabsolutedifference betweennums[i]andnums[j]is at mosttand theabsolutedifference betweeniandjis at mostk.

Example 1:

Input: nums = [1,2,3,1], k = 3, t = 0
Output: true

Example 2:

Input: nums = [1,0,1,1], k = 1, t = 2
Output: true

Example 3:

Input: nums = [1,5,9,1,5,9], k = 2, t = 3
Output: false

Solution

Solution that would take a lot of time.

public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
    for (int i = 0; i < nums.length; ++i) {
        for (int j = Math.max(i - k, 0); j < i; ++j) {
            if (Math.abs(nums[i] - nums[j]) <= t) return true;
        }
    }
    return false;
}

More optimized solution using binary search tree.

Solution using buckets.

Last updated

Was this helpful?