[LeetCode] Increasing Triplet Subsequence

简介: 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

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.

解题思路

初始化时设置n1、n2为0x7fffffff。遍历数组:

  • 若n小于等于n1,则n1=n;
  • 否则,若n小于等于n2,则n2=n;
  • 否则,返回true;

该过程不断缩小n1、n2,最后查看是否具有比n1、n2都小的数。

实现代码

// Runtime: 1 ms
public class Solution {
    public boolean increasingTriplet(int[] nums) {
        int n1 = 0x7fffffff;
        int n2 = 0x7fffffff;
        for (int n : nums) {
            if (n <= n1) {
                n1 = n;
            } else if (n <= n2) {
                n2 = n;
            } else {
                return true;
            }
        }

        return false;
    }
}
目录
相关文章
|
5月前
Leetcode 516. Longest Palindromic Subsequence
找到一个字符串的最长回文子序列,这里注意回文子串和回文序列的区别。子序列不要求连续,子串(substring)是要求连续的。leetcode 5. Longest Palindromic Substring就是求连续子串的。
22 0
LeetCode contest 183 5376. 非递增顺序的最小子序列 Minimum Subsequence in Non-Increasing Order
LeetCode contest 183 5376. 非递增顺序的最小子序列 Minimum Subsequence in Non-Increasing Order
|
索引
LeetCode 392. Is Subsequence
给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的一个子序列,而"aec"不是)。
65 0
LeetCode 392. Is Subsequence
LeetCode 376. Wiggle Subsequence
如果连续数字之间的差严格地在正数和负数之间交替,则数字序列称为摆动序列。第一个差(如果存在的话)可能是正数或负数。少于两个元素的序列也是摆动序列。
69 0
LeetCode 376. Wiggle Subsequence
|
算法
LeetCode 334. Increasing Triplet Subsequence
给定一个未排序的数组,判断这个数组中是否存在长度为 3 的递增子序列。 数学表达式如下: 如果存在这样的 i, j, k, 且满足 0 ≤ i < j < k ≤ n-1, 使得 arr[i] < arr[j] < arr[k] ,返回 true ; 否则返回 false 。
65 0
LeetCode 334. Increasing Triplet Subsequence
|
算法
LeetCode 300. Longest Increasing Subsequence
给定一个无序的整数数组,找到其中最长上升子序列的长度。
34 0
LeetCode 300. Longest Increasing Subsequence
【LeetCode】Increasing Triplet Subsequence(334)
  Given an unsorted array return whether an increasing subsequence of length 3 exists or not in the array.
79 0

热门文章

最新文章