LeetCode 75: 334. Increasing Triplet Subsequence

김준수·2024년 2월 17일
0

LeetCode 75

목록 보기
8/63
post-custom-banner

334. Increasing Triplet Subsequence

Description

Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.

정수 배열 nums가 주어진다, 만약 i < j < k 그리고 nums[i] < nums[j] < nums[k]를 만족하는 (i, j, k) 목록이 있다면 true를 return 하시오. 목록을 찾지 목한다면, false를 반환하시오

Example 1:

Input: nums = [1,2,3,4,5]
Output: true
Explanation: Any triplet where i < j < k is valid.

Example 2:

Input: nums = [5,4,3,2,1]
Output: false
Explanation: No triplet exists.

Example 3:

Input: nums = [2,1,5,0,4,6]
Output: true
Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.

Constraints:

1 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1

Follow up: Could you implement a solution that runs in O(n) time complexity and O(1) space complexity?

Solution

class Solution {
    public boolean increasingTriplet(int[] nums) {
        int i = Integer.MAX_VALUE, j = Integer.MAX_VALUE, k = Integer.MAX_VALUE;
        for (int index = 0; index < nums.length - 1; index++) {
            if (nums[index] < nums[index + 1]) {
                k = nums[index + 1];
                if (i < k && j < k) 
                    return true;
                i = nums[index];
                j = nums[index + 1];
        }
            if (i < nums[index+1])
                j = nums[index+1];
        }
        return false;
    }
}
post-custom-banner

0개의 댓글