练习题 (九)

题目:

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 difference between nums[i] and nums[j] is at most t and the difference between i and j is at most k.

解答:

class Solution 
{
public:
    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) 
    {
        if ((nums.size() < 2) || (k <= 0) || (t < 0))
        {
            return false;
        }

        // This multiset is essentially a BST which stores all the numbers 
        // within the window of size k + 1. Note that we have to use long 
        // instead of int since we have to handle the possible overflow of 
        // nums[i] + t.
        multiset<long> numBst;

        for (int i = 0; i < nums.size(); i++)
        {   
            if (i >= k + 1)
            {
                // Delete the number which falls out of the window of size k + 1.
                auto itDelete = numBst.find(static_cast<long>(nums[i - (k + 1)]));
                numBst.erase(itDelete);
            }

            // Check whether numBst contains some number between nums[i] - t 
            // and nums[i] + t (inclusive).
            auto itLower = numBst.lower_bound(
                static_cast<long>(nums[i]) - static_cast<long>(t));
            if ((itLower != numBst.end()) && 
                (*itLower <= static_cast<long>(nums[i]) + static_cast<long>(t)))
            {
                return true;
            }

            // Insert nums[i] into the BST.
            numBst.insert(static_cast<long>(nums[i]));
        }

        return false;
    }
};

心得:这里的需要用到set容器,然后最初的先排序,再找出距离最远的两个数,看两个数的差距有没有大于等于t,这个想法,进化为用low_bound()函数来实现。

函数lower_bound()在first和last中的前闭后开区间进行二分查找,返回大于或等于val的第一个元素位置。如果所有元素都小于val,则返回last的位置。

原文地址:https://www.cnblogs.com/ender-cd/p/4619079.html