leetcode刷题笔记334题 递增的三元子序列

leetcode刷题笔记334题 递增的三元子序列

地址:334. 递增的三元子序列

问题描述:

给定一个未排序的数组,判断这个数组中是否存在长度为 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

//通过记录两个较小的数,如果存在比这两个数更小的数,则必然存在三个数满足题目要求
//需要注意的是使用等号过滤最小值
object Solution {
    def increasingTriplet(nums: Array[Int]): Boolean = {
        var frist = Int.MaxValue
        var second = Int.MaxValue

        for (num <- nums) {
            if (num <= frist) {
                frist = num
            } else if (num <= second) {
                second = num
            } else {
                return true
            }
        }

        return false
    }
}
func increasingTriplet(nums []int) bool {
    first := math.MaxInt32
    secode := math.MaxInt32

    for _, num := range nums {
        if num <= first {
            first = num
        } else if num <= secode {
            secode = num
        } else {
            return true
        }
    }

    return false
}
posted @ 2020-12-17 12:45  ganshuoos  阅读(56)  评论(0编辑  收藏  举报