Awesome java python solution


  • 0
    F

    in java

        public boolean find132pattern(int[] nums) {
    //        e3 stores the second largest element
            int e3 = Integer.MIN_VALUE;
    //        stack.top() stores the largest element
            Stack<Integer> stack = new Stack<>();
            for (int i = nums.length - 1; i >= 0; i--) {
                /**nums[i] stores the smallest element
                 * if nums[i]<e3, which means e3 has been updated,
                 * because e3 is initialized to Integer.MIN_VALUE.
                 * also means an element larger than e3 has been
                 * pushed into the stack. Therefore,
                 * nums[i]<e3<stack.top()
                 * return true.
                 *
                 */
                if (nums[i] < e3) {
                    return true;
                }
                while (!stack.isEmpty() && nums[i] > stack.peek()) {
                    e3 = stack.pop();
                }
                stack.push(nums[i]);
            }
            return false;
        }
    

    in python

        def find132pattern1(self, nums):
            e3, st = float('-inf'), []
            for e in nums[::-1]:
                if e < e3:
                    return True
                while st and e > st[-1]:
                    e3 = st.pop()
                st.append(e)
            return False
    

Log in to reply
 

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