334. Increasing Triplet Subsequence
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.
Credits:
Special thanks to?@DjangoUnchained?for adding this problem and creating all test cases.
Subscribe?to see which companies asked this question
這道題要求一個沒有排序的數組中是否有3個數字滿足前后遞增的關系。最簡單的辦法是動態規劃,設置一個數組dp,dp[i]表示在i位置之前小于或者等于數字nums[i]的數字的個數。我們首先將數組dp的每個元素初始化成1.然后開始遍歷數組,對當前的數字nums[i],如果存在nums[j]<nums[i] (j<i),那么更新dp[i]=max(dp[i],dp[j]+1).如果在更新dp[i]之后,dp[i]的值為3了,那么就返回true,否則返回false。
代碼如下:
?
來自為知筆記(Wiz)
轉載于:https://www.cnblogs.com/zhoudayang/p/5246148.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的334. Increasing Triplet Subsequence的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SyntaxError: Non-UTF
- 下一篇: react判断点击位置是否为组件内,实现