Leetcode 456. Pattern

Source: Internet
Author: User

The title is to give you a bunch of numbers inside the array, whether you can find such three numbers, the first number is smaller than the third number, the second is the largest. For example, 1, 3, 2 or 4, 9, 5 This, the numbers can be discontinuous together, but to ensure that the order is unchanged, as long as there is such a group of numbers can be.

This problem I did one hours did not think of a better way, to see the other people's ideas, to understand the coming back to achieve their own, have to say, the idea is really excellent.

The idea is this, since it is three number comparison, I find the middle number is 2 that number, and then find a bigger than 2, and then find a smaller than 2, so there is such a group of numbers. How can you ensure that the order is OK, from the back of the array, to set a temporary variable temp and a stack, temp to save 2 this number, stack inside to save can be 3 this number, each traversal to a new number Curr, first compare this number has stack[-1] big, If large, put the stack inside all the smaller than the current number of the stack temp = Stack.pop (), the current number into the stack. So temp is a smaller number than the stack, the stack is a large number, because it is traversed from the back and the temp is from the stack, so the order is not a problem. Now repeat the process until you find a number that is smaller than temp, and the number is found.

Two places to take care of it.

Why is the while loop out stack changed to if yes?

You can consider a group of numbers [2, 4, 2, 3]

The second temp = Stack.pop () Here is how to understand why the last number of POPs can become temp, before the number that goes out?

You can also consider such a group of numbers [2, 4, 2, 3]

Ha ha haha

Leetcode 456. Pattern

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.