A 8ms cpp solution by a beginner


  • 0
    Z

    In my solution, I keep a vector(v) of 2 elemens which satisfy 2 rules:

    1, v[0] < v[1]

    2, v[1] is as small as possible

    So if the next element if bigger than v[1], then the answer is true. If not, continue to keep v.

    class Solution {
    public:
    bool increasingTriplet(vector<int>& nums) {
        int length = nums.size();
    	
    	if(size<3)
    		return 0;
    	
    	vector<int> v;
    	int minVal;
    	v.push_back(nums[0]);
    	minVal = nums[0];
    	
    	for(int i=1;i<size();i++){
    		if(minVal>nums[i])
    			minVal = nums[i];
    		
    		if(v.size()==1){
    			if(nums[i]>v[0])
    				v.push_back(nums[i]);
    			else if(minVal!=v[0]){
    				v.clear();
    				v.push_back(minVal);
    			}
    		}
    		else{
    			if(nums[i]>v[0]&&nums[i]<v[1]){
    				v.pop_back();
    				v.push_back(nums[i]);					
    			}
    			else if(nums[i]>minVal&&nums[i]<v[1]){
    				v.clear();
    				v.push_back(minVal);
    				v.push_back(nums[i]);
    			}
    			else if(nums[i]>v[1])
    				return 1;
    		}
    	}
    	return 0;
    }
    };

Log in to reply
 

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