LeetCode-334.-遞增的三元子序列
334. 遞增的三元子序列
難度中等315收藏分享切換為英文接收動(dòng)態(tài)反饋
給你一個(gè)整數(shù)數(shù)組 nums
贷腕,判斷這個(gè)數(shù)組中是否存在長(zhǎng)度為 3
的遞增子序列甩苛。
如果存在這樣的三元組下標(biāo) (i, j, k)
且滿足 i < j < k
吩案,使得 nums[i] < nums[j] < nums[k]
,返回 true
欠啤;否則熄阻,返回 false
膘掰。
示例 1:
輸入:nums = [1,2,3,4,5]
輸出:true
解釋:任何 i < j < k 的三元組都滿足題意
示例 2:
輸入:nums = [5,4,3,2,1]
輸出:false
解釋:不存在滿足題意的三元組
示例 3:
輸入:nums = [2,1,5,0,4,6]
輸出:true
解釋:三元組 (3, 4, 5) 滿足題意跪另,因?yàn)?nums[3] == 0 < nums[4] == 4 < nums[5] == 6
提示:
1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
進(jìn)階:你能實(shí)現(xiàn)時(shí)間復(fù)雜度為 O(n)
拧抖,空間復(fù)雜度為 O(1)
的解決方案嗎?
class Solution {
public static boolean increasingTriplet(int[] arr) {
if (arr == null || arr.length < 3) {
return false;
}
int[] ends = new int[3];
ends[0] = arr[0];
int right = 0;
int l = 0;
int r = 0;
int m = 0;
for (int i = 1; i < arr.length; i++) {
l = 0;
r = right;
while (l <= r) {
m = (l + r) / 2;
if (arr[i] > ends[m]) {
l = m + 1;
} else {
r = m - 1;
}
}
right = Math.max(right, l);
if (right > 1) {
return true;
}
ends[l] = arr[i];
}
return false;
}
}
image