题目:
给定一个未排序的数组,判断这个数组中是否存在长度为 3 的递增子序列。
数学表达式如下:
如果存在这样的 i, j, k, 且满足 0 ≤ i < j < k ≤ n-1,
使得 arr[i] < arr[j] < arr[k] ,返回 true ; 否则返回 false 。
说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1) 。
示例 1:
输入: [1,2,3,4,5]
输出: true
示例 2:
输入: [5,4,3,2,1]
输出: false
链接:https://leetcode-cn.com/problems/increasing-triplet-subsequence
思路:
1、需要注意的是判断的是递增的子序列,并不是要求递增的连续子序列
2、遍历整个数组,定义first、second两个变量,分别表示最小元素和第二小元素,如果存在第三个元素使得其大于第二小元素,则满足题目要求条件,即存在递增的三元子序列
Python代码:
class Solution(object):
def increasingTriplet(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
first = float('inf') # 记录最小元素
second = float('inf') # 记录第二小元素
for num in nums:
if num<=first:
first = num
elif num<=second:
second = num
else:
return True
return False
C++代码:
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int first = INT_MAX;
int second = INT_MAX;
for (int num : nums){
if(num<=first){
first = num;
}else if (num<=second){
second = num;
}else{
return true;
}
}
return false;
}
};
网友评论