Java Recursive


  • 0
    M
    public class Solution {
        private int len;
        
        private void helper(int[] t, int i, int n) {
            if (i < 3)
                if (i >= len) {
                    len++;
                    t[i] = n;
                } else if (n > t[i]) {
                    helper(t, i+1, t[i]);
                    t[i] = n;
                } else if (n < t[i])
                    helper(t, i+1, n);
        }
        
        public int thirdMax(int[] nums) {
            int t[] = new int[3];
            len = 0;
            
            for (int n: nums)
                helper(t, 0, n);
            
            return (len>2)? t[2]:t[0];
        }
    }
    

    Note that the actual length of the array should be stored and updated.


Log in to reply
 

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