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.
Note: Your algorithm should run in O(n) time complexity and O(1) space complexity.
Example 1:
Input: [1,2,3,4,5]
Output: true
Example 2:
Input: [5,4,3,2,1]
Output: false
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/increasing-triplet-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
找一个数组中,是否有无需连续的三个数字是递增。
class Solution {
public boolean increasingTriplet(int[] nums) {
if (nums.length <= 2) {
return false;
}
int first = nums[0];
int index = 1;
int second = 0;
int maybeFirst = Integer.MAX_VALUE;
int maybeSecond = 0;
// 找到两个递增的数字。
while (index < nums.length) {
if (nums[index] > first) {
second = nums[index];
break;
} else {
first = nums[index];
}
index++;
}
if (index >= nums.length - 1) {
return false;
}
index++;
while (index < nums.length) {
// 数字比第二个大,直接返回true
if (nums[index] > second) {
return true;
} else {
// 数字比第一个大且比第二个小,更新第二个数字
if (nums[index] < second && nums[index] > first) {
second = nums[index];
// 数字比前两个都小,则更新maybeFirst,说明它可能是下个前二数字。
// 如果数字比maybeFirst大,那么两个数字就都更新
} else if (nums[index] > maybeFirst){
first = maybeFirst;
second = nums[index];
} else {
maybeFirst = nums[index];
}
}
index++;
}
return false;
}
}
本文介绍了一个算法,用于在未排序数组中查找是否存在长度为3的递增子序列,该算法的时间复杂度为O(n),空间复杂度为O(1)。通过实例演示了算法的工作原理。
4726

被折叠的 条评论
为什么被折叠?



