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

Middle-题目44:334. Increasing Triplet Subsequence

2016-05-31 16:05 477 查看
题目原文:

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.

题目大意:

给出一个数组,判断是否存在一个递增的长度为3的子序列。

题目分析:

(1) 朴素解法:O(n3)暴力搜索;

(2) 最长递增子列:引用Middle-题目33的方法判断最长递增子列的长度是否>=3,最好的时间复杂度是O(nlogn)。

(3) O(n)算法:扫描一遍数组,令a1是当前最小值,a2是a1以后次小值,则如果当前的数比a2还大,就存在。

源码:(language:java)

public class Solution {
public boolean increasingTriplet(int[] nums) {
int a1 = Integer.MAX_VALUE,a2 = Integer.MAX_VALUE;
for(int num : nums) {
if(num<=a1)
a1=num;
else if(num<=a2)
a2=num;
else
return true;
}
return false;
}
}


成绩:

1ms,beats 34.32%,众数1ms,65.68%
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: