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
return
Given
return
第一想法就是采用动态规划的思想做,但是时间和空间都超时了。因为这里限定了长度是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;
}
};
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;
}
};
相关文章推荐
- Candy [leetcode] O(n)时间复杂度,O(1)空间复杂度的方法
- LeetCode 334 Increasing Triplet Subsequence (两种方法)
- 算法的时间复杂度和空间复杂度的求解方法
- Candy [leetcode] O(n)时间复杂度,O(1)空间复杂度的方法
- 各种排序方法的时间复杂度、空间复杂度和稳定性统计表
- 七种排序方法(稳定性、空间复杂度、时间复杂度)分析总结
- 算法度量方法——时间复杂度及空间复杂度
- bsd strtok实现和windowstrtok实现 NetBSD的方法是节约了空间,牺牲了时间(它的时间复杂度为N2) 而微软的方法是节约了时间(它的时间复杂度为N),牺牲了空间(开了一
- Candy [leetcode] O(n)时间复杂度,O(1)空间复杂度的方法
- 减少Flex应用加载时间的几种方法
- C语言的算法的时间与空间复杂度
- 算法复杂度——时间复杂度和空间复杂度
- 常用的排序算法的时间复杂度和空间复杂度
- 时间复杂度和空间复杂度
- 算法的时间复杂度和空间复杂度
- 时间复杂度和空间复杂度
- Qt configure 参数不完全说明 以及 精简系统 减少编译时间的一些方法
- 时间复杂度和空间复杂度
- IIS假死的解决方法 缩短IIS应用池回收时间来实现减少IIS假死
- 动态规划求数组中和最大字串的值 以及 字符串的循环移位(要求空间复杂度O(1),时间复杂度O(n))