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 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.

  题干的意思是给定未排序数组,从中找到三个满足arr[i] < arr[j] < arr[k] given 0 ≤ i < j < k ≤ n-1递增数字时返回true,找不到返回false。

解题思路:

  设定两个数字min和middle,min保存已发现的最小值,middle保存仅比min大的第二小值。

if num <= minmin = num
else if num <= middlemiddle = num
elsereturn true;原因是 此时的num 肯定比min,middle都大,有min < middle < num

  源码如下:

/**
 * Increasing Triplet Subsequence
 * @param nums
 * @return
 */
public boolean increasingTriplet(int[] nums) {
    int min = Integer.MAX_VALUE;
    int middle = Integer.MAX_VALUE;
    for (int num : nums) {
        if (num <= min) {
            min = num;
        } else if (num <= middle) {
            middle = num;
        } else {
            return true;
        }
    }
    return false;
}
发布了47 篇原创文章 · 获赞 31 · 访问量 12万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章