Java simple solution sorting array


  • 0

    First sort the array in ascending order, then save the maximum value in case there is no thirdMax number. Then iterate through the array and find the third max value.

    public class Solution {
        public int thirdMax(int[] nums) {
            if(nums == null || nums.length == 0)
                return 0;
            
            Arrays.sort(nums);
    
            int ret = nums[nums.length-1];
            int count = 2;
            
            for(int i = nums.length-2; i >= 0; i--)
            {
                if(nums[i] != nums[i+1])
                {
                    count --;
                }
                if(count == 0)
                {
                    ret = nums[i];
                    break;
                }
                 
            }
            return ret;
        }
    }
    

Log in to reply
 

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