LeetCode220. Contains Duplicate III

Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.

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

思路:

这道题如果我们直接使用暴力求解的话会导致超时,所以我们这里借鉴了别人的文章:here。这里的重点在于公式:

如果 x < nums[i] - t;

则 nums[i] - x > t。

这样我们就可以通过找边界来处理这个问题了。

1 使用map实现:

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
		int len = int(nums.size());
		map<long, int> m;
		int j = 0;
		for (int i = 0; i < len; i++) {
			if (i - j > k) m.erase(nums[j++]);
			auto it = m.lower_bound(long(nums[i]) - t);
			if (it != m.end() && it->first - nums[i] <= t) return true;
			m[nums[i]] = i;
		}
		return false;
    }
};

2 使用multiset实现:

class Solution {
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {
		int len = int(nums.size());
		multiset<long> m;
		int j = 0;
		for (int i = 0; i < len; i++) {
			if (i - j > k){
                auto it = m.find(nums[j++]);
                m.erase(it);
            }
			auto it = m.lower_bound(long(nums[i]) - t);
			if (it != m.end() && *it - nums[i] <= t) return true;
			m.insert(nums[i]);
		}
		return false;
    }
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/89404878