LeetCode: The third largest number

Title description

Give you a non-empty array and return the third largest number in this array   . If it does not exist, return the largest number in the array

Ideas

  • First sort the array in descending order
  • There may be duplicate elements in the array, then we use a flag to record , traverse the array, if the current element and the next element are not equal, then flag++, when flag==2, then the array has the third largest number, return The next element
  • If the above situation is not met, then it means that there is no third largest element , directly return nums[0] , the largest number is enough

Code

class Solution {
    public int thirdMax(int[] nums) {
        for(int bound=0;bound<nums.length;bound++){
            for(int cur=nums.length-1;cur>bound;cur--){
                if(nums[cur]>nums[cur-1]){
                    int temp=nums[cur];
                    nums[cur]=nums[cur-1];
                    nums[cur-1]=temp;
                }
            }
        }
        int flag=0;
        for(int i=0;i<nums.length-1;i++){
            if(nums[i]!=nums[i+1]){
                flag++;
            }
            if(flag==2){
                return nums[i+1];
            }
        }
        return nums[0];       
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_43939602/article/details/114212351