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

334.leetcode Increasing Triplet Subsequence(medium)[巧妙的方法减少时间与空间复杂度]

2016-10-07 21:47 330 查看
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,因此保存在目前为止最小和第二小的数,然后检查数组中是否有比这两个数大的数,如果有则找到一组3个数。

class Solution {
public:

bool increasingTriplet(vector<int>& nums) {
int n = nums.size();
if(n<3) return false;
int min =2147483647, min2 = 2147483647;
for(int i=0;i<n;i++)
{
if(nums[i]<=min)
min = nums[i];
else if(nums[i]<=min2)
min2 = nums[i];
else if(nums[i]>min2)
return true;
}
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: