Java solution - time complexity O(n), space complexity O(1)


  • -1
    Y

    Source code is long, but the logic is easily understandable.

        public int thirdMax(int[] nums) {
            if (nums == null)
                return Integer.MAX_VALUE;
                
            boolean f = false, s = false, t = false;
            
            int first = 0;
            int second = 0;
            int third = 0;
            
            for (int i = 0; i < nums.length; i++) {
                if (!f || !s || !t) {
                    if (!f) {
                        first = nums[i];
                        f = true;
                    } else if (!s) {
                        if (nums[i] != first) {
                            if (nums[i] > first) {
                                second = first;
                                first = nums[i];
                            } if (nums[i] < first) {
                                second = nums[i];
                            }
                            s = true;
                        }
                    } else {
                        if (nums[i] != first && nums[i] != second) {
                            if (nums[i] > first) {
                                third = second;
                                second = first;
                                first = nums[i];
                            } else if (nums[i] > second) {
                                third = second;
                                second = nums[i];
                            } else
                                third = nums[i];
                            t = true;
                        }
                    }
                } else if (nums[i] != first && nums[i] != second && nums[i] != third) {
                    if (nums[i] > first) {
                        third = second;
                        second = first;
                        first = nums[i];
                    } else if (nums[i] > second) {
                        third = second;
                        second = nums[i];
                    } else if (nums[i] > third) {
                        third = nums[i];
                    }
                }
            }
    
            if (t) return third;
            if (f || s) return first;
            
            return Integer.MAX_VALUE;
        }
    

Log in to reply
 

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