leetCode---Increasing Triplet Subsequence
来源:互联网 发布:nginx 指定配置文件 编辑:程序博客网 时间:2024/05/29 12:48
一. 题目:Increasing Triplet Subsequence
Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
More specifically, if there exists i, j, k such that arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1 return true else return false.
Your function 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的递增子序列。形式上,函数应当:如果存在这样的i, j, k(0 ≤ i < j < k ≤ n-1),使得arr[i] < arr[j] < arr[k],返回true,否则返回false。
我们可以这样考虑,在扫描的时候提供一个下界(low)和上界(high),当设置上界后,如果找到大于上界的元素时,此时表示数组中存在满足条件的序列。当找到形式nums[i] > nums[i - 1]的元素时,可以推断出如果上界存在时,一定有nums[i] < nums[high],当上界不存在时,此时直接更新。而这一组值做为新的上界与下界,效果与未更新时相同,且包涵了新的更大的范围。如果不满足以上情况,在nums[i]在上界与下界的范之中时,我们更新上界,扩大范围。代码如下:
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 (high != -1 && nums[i] > nums[high]) { return true; } 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]) { high = i; } } return false; }};
- leetcode Increasing Triplet Subsequence
- LeetCode - Increasing Triplet Subsequence
- [LeetCode] Increasing Triplet Subsequence
- LeetCode Increasing Triplet Subsequence
- Leetcode:Increasing Triplet Subsequence
- LeetCode:Increasing Triplet Subsequence
- leetcode:Increasing Triplet Subsequence
- [LeetCode]Increasing Triplet Subsequence
- Leetcode Increasing Triplet Subsequence
- 【LeetCode】Increasing Triplet Subsequence
- leetcode increasing-triplet-subsequence
- leetcode Increasing Triplet Subsequence
- 【Leetcode】Increasing Triplet Subsequence
- LeetCode:Increasing Triplet Subsequence
- LeetCode Increasing Triplet Subsequence
- leetCode---Increasing Triplet Subsequence
- [leetcode] 334. Increasing Triplet Subsequence
- Leetcode 334. Increasing Triplet Subsequence
- 2. Java中的垃圾收集
- ubuntu16.10 下opencv2.4.13安装配置
- 二进制有符号数加法
- “无法为源卷创建vss快照 错误代码:2147549183”
- Mediaplayer 音乐播放
- leetCode---Increasing Triplet Subsequence
- java.sql.SQLException: Unsupported character encoding 'UTF-8;'.
- SVN 并行开发项目管理
- Spark MLlib系列(一):入门介绍
- python2.7基于selenium的web自动化测试项目--house目录
- 微信企业号已经认证了就不能更改名称了
- root-MUSIC算法
- iOS 循环引用问题解决方案
- 给 Java 初学者的学习路线建议