Given an integer array
Example 1:
Input: nums = [1,2,3,4,5] Output: true Explanation: Any triplet where i < j < k is valid.
Example 2:
Input: nums = [5,4,3,2,1] Output: false Explanation: No triplet exists.
Example 3:
Input: nums = [2,1,5,0,4,6] Output: true Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.
Constraints:
1 <= nums.length <= 5 * 105 -231 <= nums[i] <= 231 - 1
可以用同一個概念來解,多個檢查條件是 ans.size == 3 的時候,就回傳 true
以及結束的時候,檢查 ans.size == 3,因為有可能最後一個數字才滿足條件
Kotlin ( O(nlogn) )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun increasingTriplet(nums: IntArray): Boolean { | |
val ans = arrayListOf<Int>() | |
ans.add(nums[0]) | |
var left = 0 | |
var right = 0 | |
var mid = 0 | |
for(i in 1..nums.lastIndex) { | |
when { | |
ans.size == 3 -> return true | |
nums[i] <= ans[0] -> ans[0] = nums[i] | |
nums[i] > ans.last() -> ans.add(nums[i]) | |
else -> { | |
left = 0 | |
right = ans.size | |
while(left < right) { | |
mid = left + (right - left) / 2 | |
if(ans[mid] < nums[i]) { | |
left = mid + 1 | |
} else { | |
right = mid | |
} | |
} | |
if(right >= ans.size) { | |
ans.add(nums[i]) | |
} else { | |
ans[right] = nums[i] | |
} | |
} | |
} | |
} | |
return ans.size == 3 | |
} | |
} |
題目也有問是否可以在 time complexity O(n) 以及 space complexity O(1) 完成
看到一個很厲害的解法 ,其實就是按照題意進行
準備兩個變數,number1 和 number2,兩個的初始值都是 Int_MAX_VALUE
當有個數字小於等於 number1 的時候,不斷更新 number1
當有個數字大於 number1 且小於等於 number2 的時候,不斷更新 number2
這時候,如果還有一個數字大於 number1和 number2,那就找到答案了
kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun increasingTriplet(nums: IntArray): Boolean { | |
var number1 = Int.MAX_VALUE | |
var number2 = Int.MAX_VALUE | |
for(n in nums) { | |
when { | |
number1 >= n -> number1 = n | |
number2 >= n -> number2 = n | |
else -> return true | |
} | |
} | |
return false | |
} | |
} |
沒有留言:
張貼留言