O(n) time and O(n) space


  • 0

    Delete the first two bigger numbers one by one.

    public int thirdMax(int[] nums) {
            int m1=Integer.MIN_VALUE;
            int m2=m1;
            int m3=m2;
            List<Integer> l1=new ArrayList<>();
            List<Integer> l2=new ArrayList<>();
            for(int i=0;i<nums.length;i++){
                m1=Math.max(m1,nums[i]);
            }
            for(int i=0;i<nums.length;i++){
                if(nums[i]!=m1){
                    l1.add(nums[i]);
                }
            }
            if(l1.size()==0){
                return m1;
            }
            for(int i=0;i<l1.size();i++){
                m2=Math.max(m2,l1.get(i));
            }
            for(int i=0;i<l1.size();i++){
                if(l1.get(i)!=m2){
                    l2.add(l1.get(i));
                }
            }
            if(l2.size()==0){
                return m1;
            }
            for(int i=0;i<l2.size();i++){
                m3=Math.max(m3,l2.get(i));
            }
            return m3;
        }
    

Log in to reply
 

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