Java solution in O(n) time and O(1) space


  • 0
    S
    public class Solution {
        public int thirdMax(int[] nums) {
            long first = Long.MIN_VALUE;
            long second = Long.MIN_VALUE;
            long third = Long.MIN_VALUE;
            
            for (int num : nums) {
                if (num > third) {
                    if (num > second) {
                        if (num > first) {
                            third = second;
                            second = first;
                            first = num;
                        } else {
                            if (first != num) {
                                third = second;
                                second = num;
                            }
                        }
                    } else {
                        if (second != num) {
                            third = num;
                        }
                    }
                }
            }
            
            return third == Long.MIN_VALUE ? (int) first : (int) third;
        }
    }

Log in to reply
 

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