clean and common binary search solution

  • 0
    class Solution {
        int binarySearch(int right,int val,vector<int>&res)
                int left = 0;
                if(left>right) return -1;
                    int mid = left+(right-left)/2;
                    if(res[mid]>val)    right=mid-1;
                    else if(res[mid]<val)   left = mid+1;
                    else    return mid;
                return left>res.size()-1?-1:left;
        bool increasingTriplet(vector<int>& nums) {
            if(nums.size()==0)  return false;
            int size = nums.size();
            for(int i=0;i<size;i++)
                int idx = binarySearch(res.size()-1,nums[i],res);
                if(idx==-1) res.push_back(nums[i]);
                else    res[idx] = nums[i];
                if(res.size()>=3)   return true;//you can change 3 to what the question require!
            return false;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.