Java fast and easy understand solution using sort


  • 0
    M
    public class Solution {
        public int thirdMax(int[] nums) {
            Set<Integer> hs = new HashSet<Integer>();
            List<Integer> list = new ArrayList<Integer>();
            Arrays.sort(nums);
            int d=0, res = nums[0];
            for(int i=nums.length-1; i>=0; i--){
                if(hs.add(nums[i])){
                    list.add(nums[i]);
                    d++;
                }
                if(d==3){
                    res = nums[i];
                    break;
                }
            }
            if(d==2)    res = list.get(0)>list.get(1) ? list.get(0):list.get(1);
            return res;
        }
    }
    

Log in to reply
 

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