C+, another way :find the third smallest element


  • 0
    L

    Using smallest and 2ndsmallest approach. As soon as you find the third smallest, you have it!

        //smallestsofar
        //samllersofar
        
        int sz = nums.size();
        if(sz <3) return false;
        
        int smallestsofar=nums[0];
        int smaller=INT_MAX;
        for( int i =1; i< sz ; i++)
        {
            smallestsofar = min(smallestsofar, nums[i]);
            smaller = min(smaller, nums[i]>smallestsofar? nums[i] : smaller);
            if(nums[i] > smaller) return true;
        }
        return false;
        
     
        
        // 1lenmin;
        // 2lenmin;
        // 1lenmin = min ( a[i], 1lenmin)
        // 2lenmin = if (a[i] > 1lenmin) 2lenmin = min (a[i], 2lenmin)
        // 3lenmin = if( a[i] > 2lenmin) 3lenmin =  min (a[i], 3lenmin)
        
        int onelenmin=INT_MAX;
        int twolenmin=INT_MAX;
        
        for(int i=0;i<nums.size() ;i++)
        {
            
           onelenmin= min(nums[i],onelenmin) ;
           if( nums[i] > onelenmin) twolenmin = min(nums[i], twolenmin);
           if( nums[i] > twolenmin) return true;
        }
        return false;

Log in to reply
 

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