Leetcode, leetcodeoj

Source: Internet
Author: User

Leetcode, leetcodeoj

Question:

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.


Analysis:

Use multiset to perform binary search of BST. Lower_bound () returns an iterator pointing to the first element greater than or equal to the input value.

Scans the array from left to right. If the number of elements in multiset is k + 1, delete the first element. Because multiset. size () is always less than or equal to k + 1, the subscript difference must be less than or equal to k. Then, use lower_bound () to find the first element that is greater than or equal to nums [I]-t. If the absolute value of the difference between this element and nums [I] is less than or equal to t, true is returned.

 Note: To prevent overflow, data must be converted to long for processing!

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;    }};






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.