Leetcode Increasing Triplet Subsequence
2016-04-24 18:02
459 查看
Leetcode Increasing Triplet Subsequence,本题主要的难点是如何使用o(n)的方法进行判别。
我们可以这样考虑,在扫描的时候提供一个下界(low)和上界(high),他们的初始值都不存在,并且在扫描时进行更新,更新方法如下:
当设置上界后,如果找到大于上界的元素时,此时表示数组中存在满足条件的序列。
当找到形式nums[i] > nums[i - 1]的元素时,可以推断出如果上界存在时,一定有nums[i] < nums[high],当上界不存在时,此时直接更新。而这一组值做为新的上界与下界,效果与未更新时相同,且包涵了新的更大的范围。
如果不满足以上情况,在nums[i]在上界与下界的范之中时,我们更新上界,扩大范围。
相关cpp代码如下:
我们可以这样考虑,在扫描的时候提供一个下界(low)和上界(high),他们的初始值都不存在,并且在扫描时进行更新,更新方法如下:
当设置上界后,如果找到大于上界的元素时,此时表示数组中存在满足条件的序列。
当找到形式nums[i] > nums[i - 1]的元素时,可以推断出如果上界存在时,一定有nums[i] < nums[high],当上界不存在时,此时直接更新。而这一组值做为新的上界与下界,效果与未更新时相同,且包涵了新的更大的范围。
如果不满足以上情况,在nums[i]在上界与下界的范之中时,我们更新上界,扩大范围。
相关cpp代码如下:
#include<iostream> #include<vector> using namespace std; class Solution { public: bool increasingTriplet(vector<int>& nums) { if (nums.size() < 3) { return false; } int low = 0; int high = -1; for (int i = 1; i < nums.size(); i++) { // if there is a element great than the high bound value if (high != -1 && nums[i] > nums[high]) { return true; } // update the lower bound and higher bound if (nums[i] > nums[i - 1]) { low = nums[i - 1] < nums[low]? i - 1 : low; high = i; } else if (high != -1 && nums[i] < nums[high] && nums[i] > nums[low]) { // update the higher bound high = i; } } return false; } }; int main(int argc, char* argv[]) { Solution so; vector<int> test; for (int i = 1; i < argc; i++) { test.push_back(atoi(argv[i])); } cout<<"resutl: "<<so.increasingTriplet(test)<<endl; return 0; }
测试:./a.out 2 1 5 0 3 4 result: 1
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解