(Java) Leetcode 334. Increasing Triplet subsequence--increment of ternary subsequence

Source: Internet
Author: User

Given an unsorted array return whether a increasing subsequence of length 3 exists or not in the array.

Formally the function should:

Return True if there exists I, J, K
such that Arr[i] < arr[j] < arr[k] given 0≤ i < J < kn-1 else return false.

Your algorithm should run in O (n) time complexity and O (1) space complexity.

Examples:
Given [1, 2, 3, 4, 5] ,
Return true .

Given [5, 4, 3, 2, 1] ,
Return false .

This problem and Leetcode 300. Longest increasing subsequence--the longest ascending subsequence is actually the same, but increases the limitation of time and space complexity. In fact, because just to determine if there is a ternary increment sequence, then when the list of elements reached three, you can return to ture, and every time you look for replacement elements only in two select a large, so so-called two search is actually only used in the constant number of times. So in fact, based on the No. 300 question slightly modified to get the code can be passed.

Optimization is actually the modification of the process to translate, set two variables num1,num2, initially set to the maximum value. Traversing the array, if there is smaller than the NUM1, the num1 into that element, if there is larger than the NUM1 and smaller than the num2, the num2 replaced, these two steps are actually in the simulation of the No. 300 element of the replacement. Finally, when there are larger numbers than NUM1 and num2, then you can return true directly, which is equivalent to simulating list.size () = = 3.

Java

classSolution { Public BooleanIncreasingtriplet (int[] nums) {        intNUM1 = integer.max_value, num2 =Integer.max_value;  for(inti = 0; i < nums.length; i++)        {            if(Nums[i] < NUM1) NUM1 =Nums[i]; Else if(Nums[i] > NUM1 && nums[i] < num2) num2 =Nums[i]; Else if(Nums[i] > num2)return true; }        return false; }}

(Java) Leetcode 334. Increasing Triplet subsequence--increment of ternary subsequence

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.