LeetCode 334. Increasing Triplet Subsequence
来源:互联网 发布:知乎 小程序 ui 框架 编辑:程序博客网 时间:2024/06/05 18:10
- 题目
- 题意
- 分析
- 代码
题目
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的升序子序列是否存在于数组中。
它的功能应该是:
返回true,如果存在i,j,k,使得 arr [i] < arr [j] <arr [k] ,0≤i<j<k≤n-1否则返回false。
您的算法应以O(n)时间复杂度和O(1)空间复杂度运行。
例子:
给定[1,2,3,4,5]
返回true
。
给定[5,4,3,2,1]
返回false
。
分析
这道题的意思是在一个未排序的数组中查找是否存在一个长度至少为3的升序子集。下面是需要注意的事项:
1、我们可以理解为在一个降序的数组中查找是否存在一个升序的子集。
2、这个升序可能是不连续的,比如数组[5,1,5,2,5,4]
,就存在这样的升序子序列[1,2,5]
,[1,2,4]
。
3、时间复杂度为O(n),空间复杂度为O(1)。
下文的代码利用了上述事项1,从一个降序的数组中查找一个升序子集。
1、a表示升序子集中最小的数。
2、b表示升序子集中第二小的数。
3、如我们之前所假设的,nums是一个降序的数组,如果nums[i] 大于a,且nums[i]大于b,则表示存在这样一个升序子集。return true。
4、否则,返回 false。
代码
bool increasingTriplet(vector<int>& nums) { int a = INT_MAX, b = INT_MAX; for(int i=0;i<nums.size();i++){ if(nums[i]<=a) a = nums[i]; else if(nums[i]<=b) b = nums[i]; else return true; } return false;}
61 / 61 test cases passed.
Runtime: 9 ms
- [leetcode] 334. Increasing Triplet Subsequence
- Leetcode 334. Increasing Triplet Subsequence
- leetcode 334. Increasing Triplet Subsequence
- [leetcode] 334. Increasing Triplet Subsequence
- [LeetCode]334. Increasing Triplet Subsequence
- LeetCode#334. Increasing Triplet Subsequence
- [LeetCode]334. Increasing Triplet Subsequence
- LeetCode *** 334. Increasing Triplet Subsequence
- LeetCode 334. Increasing Triplet Subsequence
- LeetCode 334. Increasing Triplet Subsequence
- Leetcode-334. Increasing Triplet Subsequence
- LeetCode-334.Increasing Triplet Subsequence
- leetcode 334. Increasing Triplet Subsequence
- [leetcode] 334. Increasing Triplet Subsequence
- LeetCode 334. Increasing Triplet Subsequence
- 【LeetCode】 334. Increasing Triplet Subsequence
- LeetCode 334. Increasing Triplet Subsequence
- [leetcode]334. Increasing Triplet Subsequence
- 数学分析八讲笔记(二)
- 存储过程+调用存储过程+无/带参的存储过程+in参数+out参数+int out参数+为参数设置默认值
- 普元EOS介绍
- Shiro 自定义核心配置文件路径
- Ceph的Paxos源码注释之 Election
- LeetCode 334. Increasing Triplet Subsequence
- 正则化项
- CF806C:Prairie Partition(二分)
- 购买vps服务器
- redis基本命令
- Kotlin初探
- 新闻客户端(AsyncHttpClient和SmartImageView的综合使用)
- xargs命令
- 关于KotLin,在学习的过程中还需要思考的问题