您的位置:首页 > 产品设计 > UI/UE

LeetCode 334. Increasing Triplet Subsequence(长度为3的递增子序列)

2016-04-29 14:37 501 查看
原题网址:https://leetcode.com/problems/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
.
方法:保存3个候选值,其中第1、2个位递增的一对,第3个位比第1个还小的数字。

public class Solution {
public boolean increasingTriplet(int[] nums) {
int count = 0;
int[] buf = new int[3];
for(int i=1; i<nums.length; i++) {
if (count == 0 && nums[i-1] < nums[i]) {
buf[0] = nums[i-1];
buf[1] = nums[i];
count = 2;
} else if (count == 2) {
if (buf[1] < nums[i]) return true;
if (buf[0] < nums[i]) {
buf[1] = nums[i];
} else if (buf[0] > nums[i]) {
buf[2] = nums[i];
count = 3;
}
} else if (count == 3) {
if (buf[1] < nums[i]) return true;
if (buf[2] >= nums[i]) {
buf[2] = nums[i];
} else {
buf[0] = buf[2];
buf[1] = nums[i];
count = 2;
}
}
}
return false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: