Leetcode - Increasing Triplet Subsequence

My code:

public class Solution {
    public boolean increasingTriplet(int[] nums) {
        int min = Integer.MAX_VALUE, secondMin = Integer.MAX_VALUE;
        for(int num : nums){
            if(num <= min) min = num;
            else if(num < secondMin) secondMin = num;
            else if(num > secondMin) return true;
        }
        return false;
    }
}

reference:
https://discuss.leetcode.com/topic/37577/my-accepted-java-solution-for-this-question-only-7-lines-clear-and-concise/2

一开始我是有疑问的:
[5,6,3,7]
我觉得按照这个算法,返回true,但本应该返回false
但后来发现,其实增长不一定要连续。

我自己也做了出来, 时间O(n), 空间 O(1)
用的还是类似于 Longest Increasing Subsequence 的想法

My code:

public class Solution {
    public boolean increasingTriplet(int[] nums) {
        if (nums == null || nums.length < 3) {
            return false;
        }
        
        int c = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] > nums[c]) {
                c++;
                nums[c] = nums[i];
            }
            else {
                int begin = 0;
                int end = c;
                while (begin <= end) {
                    int mid = begin + (end - begin) / 2;
                    if (nums[mid] > nums[i]) {
                        end = mid - 1;
                    }
                    else if (nums[mid] < nums[i]) {
                        begin = mid + 1;
                    }
                    else {
                        begin = mid;
                        break;
                    }
                }
                nums[begin] = nums[i];
            }
        }
        
        return c >= 2;
    }
}

Anyway, Good luck, Richardo! — 10/12/2016

    原文作者:Richardo92
    原文地址: https://www.jianshu.com/p/e3405a915fcf
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞