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

LeetCode -- Increasing Triplet Subsequence

2016-02-24 13:44 686 查看
Question:

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
.

Analysis:

给出一个未排序的数组,判断该数组中是否存在一个长度为3的递增数组。

要求算法时间复杂度为O(n),空间复杂度为O(1).

思路:

1. 最容易想到的思路就是3层for循环,先找出两个递增的序列,然后第三个数字比第二个数字的序号大,因此三层for循环可以很容易的解决,但是由于题目要求时间复杂度为O(n)。而这个思路的复杂度最好为O(1)前三个就符合条件,这样就返回true了,最差为O(n3)所有的都不符合条件,知道最后才会返回false。空间复杂度为0.不符合要求,但还是写上试了一下,没想到真的没有TLE!

Answer:

public class Solution {
public boolean increasingTriplet(int[] nums) {
if(nums == null || nums.length < 3)
return false;
for(int i=0; i<nums.length; i++) {
for(int j=i+1; j<nums.length; j++) {
if(nums[j] > nums[i]) {
for(int k=j+1; k<nums.length; k++) {
if(nums[k] > nums[j])
return true;
}
}
}
}
return false;
}
}


2. 题目中要求时间复杂度为O(n),因此只能遍历数组一遍而不能有嵌套for循环。同时空间复杂度为O(1),所以我们使用两个变量,第一个变量保存最小的值,第二个变量保存次小的值,当下面的数组元素有一个比当前两个变量值都大的话,就会返回true。

Answer:

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