Java: using long to check Int.MIN_VALUE, O(n) Time, O(1) Space


  • 0
    A
    public class Solution {
        public int thirdMax(int[] nums) {
            // algorithm: simply define three local variables, max1, max2, and max3; and surfacing them one by one
            long max1 = Long.MIN_VALUE;
            long max2 = Long.MIN_VALUE;
            long max3 = Long.MIN_VALUE;
    
            for (int index = 0; index < nums.length; index++) {
                int num = nums[index];
                // throw away any of the top three
                if (num == max1 || num == max2 || num == max3) continue;
                if (num > max1) {
                    max3 = max2;
                    max2 = max1;
                    max1 = num;
                } else if (num > max2) {
                    max3 = max2;
                    max2 = num;
                } else if (num > max3) {
                    max3 = num;
                }
            }
    
            return (Long.MIN_VALUE == max3) ? (int)max1 : (int)max3;
        }
    }

Log in to reply
 

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