zoukankan      html  css  js  c++  java
  • 练习题 (九)

    题目:

    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的位置。

  • 相关阅读:
    华为 VRP系统管理
    清除远程桌面登陆记录
    windows多用户登陆
    破解win7系统密码
    ms10-061漏洞复现
    通达OA任意用户登录漏洞复现(POC+手工方式实现)
    Windows五次Shift漏洞
    CODESYS V3远程堆溢出漏洞复现(环境配置+复现过程)
    工控软件DLL劫持漏洞复现
    Redis远程命令执行漏洞复现
  • 原文地址:https://www.cnblogs.com/ender-cd/p/4619079.html
Copyright © 2011-2022 走看看