[LeetCode] 334. Increasing Triplet Subsequence
Problem
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
.
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 * 10^5
-2^31 <= nums[i] <= 2^31 - 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 first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;
for (int n : nums) {
if (n <= first) first = n;
else if (n <= second) second = n;
else return true;
} return false;
}
}
Explanation
- 배열 nums의 요소들을 참조하면서 Triplet 중 가장 작은 값, 중간 값을 메모해두고 가장 큰 값이 될 수 있는 값을 만났을 때 true를 반환하면 문제를 해결할 수 있다.
- Triplet 중 가장 작은 값, 중간 값을 메모하기 위해서 변수 first와 second를 선언하고 정수형 최대값을 할당한다.
int first = Integer.MAX_VALUE, second = Integer.MAX_VALUE;
- 배열 nums의 요소들을 참조하면서 Triplet 중 가장 작은 값이 될 수 있는 수를 변수 first에 할당하고, 중간 값이 될 수 있는 수를 변수 second에 할당한다. 그리고 두 수 모두에 할당할 수 없는 숫자는 Triplet 중 가장 큰 값이 될 수 있는 수 이므로 그 때 true를 반환한다. for반복문을 나오게 되면 Triplet이 존재하지 않는 다는 의미가 되므로 false를 반환한다.
for (int n : nums) { if (n <= first) first = n; else if (n <= second) second = n; else return true; } return false;
Leave a comment