leetcode,leetcodeoj

來源:互聯網
上載者:User

leetcode,leetcodeoj

題目:

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.


分析:

    利用multiset進行BST的二分搜尋。lower_bound()返回一個迭代器,指向大於等於輸入值的第一個元素。

    從左至右掃描數組,若multiset的元素數量等於k+1,則刪去最先進入的元素。由於multiset.size()始終小於等於k+1,所以下標之差是肯定小於等於k的。然後利用lower_bound(),找到第一個大於等於nums[i]-t的元素,若該元素和nums[i]的差的絕對值小於等於t,則返回真。

  注意:為了防止溢出,必須將資料轉化為long long進行處理!

class Solution {public:    bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) {        if(nums.size()<=1 || k<1 || t<0)            return false;                    multiset<long long> mset;        long long long_t=t;                for(int i=0;i<nums.size();++i)        {            if(mset.size()==k+1)            {                auto it=mset.find(nums[i-k-1]);                mset.erase(it);            }            long long tmp=nums[i];            auto it=mset.lower_bound(tmp-long_t);            if(it!=mset.end())            {                long long diff=*it>tmp?*it-tmp:tmp-*it;                if(diff<=long_t)                    return true;            }            mset.emplace(nums[i]);        }        return false;    }};






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.