(Java) LeetCode 334. Increasing Triplet Subsequence —— 遞增的三元子序列

來源:互聯網
上載者:User

標籤:and   序列   增加   ret   solution   []   最大值   function   asi   

Given an unsorted array return whether an 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 < k ≤ n-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.

 

 

這道題和LeetCode 300. Longest Increasing Subsequence —— 最長上升子序列其實是一樣的,只是增加了時間和空間複雜度的限制。其實因為只是判斷是否有三元遞增序列,那麼當list中的元素達到三個,就可以返回ture,並且每次尋找替換元素的時候只是在兩個之中選個大的,所以所謂的二項搜尋其實也是只用了常數級的時間。所以其實基於第300題稍作修改就可以得到可以通過的代碼。

最佳化的話其實就是把修改的過程翻譯過來,設定兩個變數num1,num2,初始設為最大值。遍曆數組,如果有比num1小的,就把num1換成那個元素,如果有比num1大且比num2小的,把num2換掉,這兩步其實是在類比第300題中元素的替換。最後,當存在比num1和num2都大的數,那麼就可以直接返回true了,這一步相當於類比list.size() == 3。

 

 

Java

class Solution {    public boolean increasingTriplet(int[] nums) {        int num1 = Integer.MAX_VALUE, num2 = Integer.MAX_VALUE;        for (int i = 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 —— 遞增的三元子序列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.