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

    Credits:
    Special thanks to @DjangoUnchained for adding this problem and creating all test cases.

    Subscribe to see which companies asked this question

    class Solution {
    public:
        bool increasingTriplet(vector<int>& nums) {
            int i =  nums.size() - 1;
            if (i < 2) {
                return false;
            }
            int y = INT_MAX;
            int z = INT_MAX;
            for (; i>0; i--) {
                if (nums[i] > nums[i-1]) {
                    if (z == INT_MAX) {
                        z = nums[i];
                        y = nums[i - 1];
                    } else if (nums[i - 1] >= z) {
                        z = nums[i];
                        y = nums[i - 1];
                    } else if (nums[i - 1] > y && nums[i] > z) {
                        z = nums[i];
                        y = nums[i - 1];
                    } else if (nums[i - 1] > y && nums[i] < z) {
                        return true;
                    }else if (nums[i - 1] == y && nums[i] < z){
                        return true;
                    } else if (nums[i - 1] < y) {
                        return true;
                    }
            }
        }
        return false;
    }
    };

    自己写的太复杂了,看了别人的,凝练一下,

    class Solution {
    public:
        bool increasingTriplet(vector<int>& nums) {
            int n = nums.size();
            int a = INT_MAX;
            int b = INT_MAX;
    
            for (int i = 0; i < n; i++)
            {
                if (nums[i] <= a)
                {
                    a = nums[i];
                }
                else if (nums[i] <= b)
                {
                    b = nums[i];
                }
                else
                {
                    return true;
                }
            }
    
            return false;
        }
    };
  • 相关阅读:
    java web 初学
    学习2
    学习
    上课
    Java中字母大小写的转换
    心得体会
    servlet请求
    响应设置消息体
    servlet响应-头部信息的设置
    servlet的响应(一)
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5207722.html
Copyright © 2020-2023  润新知