상세 컨텐츠

본문 제목

334. Increasing Triplet Subsequence

LeetCode

by 10002s 2023. 10. 30. 23:25

본문

Increasing Triplet Subsequence - LeetCode

 

문제 번역: 정수 배열 nums가 주어진다. i < j < k를 만족하는 인덱스 트리플 (i, j, k)가 존재하면 nums[i] < nums[j] < nums[k]인 경우 true를 반환하라. 그러한 인덱스가 존재하지 않으면 false를 반환하라.

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.
문제 요약:

정수 배열에서 연속된 세 숫자를 찾아야 하며, 이들이 증가하는 순서를 가져야 합니다. 즉, i < j < k 이고 nums[i] < nums[j] < nums[k]인 경우 true를 반환합니다. 그렇지 않으면 false를 반환합니다.

풀이 과정:
  1. 가장 작은 값(min1)과 그 다음으로 작은 값(min2)을 추적하는 두 변수를 초기화합니다. 이 두 변수를 초기화하는 이유는 세 숫자를 찾아야 하기 때문입니다.
  2. 배열을 순회하며 다음 작업을 수행합니다.
    - 현재 값(num)이 min1보다 작으면 min1을 갱신합니다.
    - 현재 값(num)이 min1보다 크고 min2보다 작으면 min2를 갱신합니다.
    - 현재 값(num)이 min2보다 크면 세 숫자가 존재하므로 true를 반환합니다.
  3. 배열 순회가 끝날 때까지 세 숫자가 발견되지 않으면 false를 반환합니다.
class Solution {
    public boolean increasingTriplet(int[] nums) {
        int min1 = Integer.MAX_VALUE;
        int min2 = Integer.MAX_VALUE;

        for(int num : nums){
            if(num <= min1){
                min1 = num;
            }else if(num <= min2){
                min2 = num;
            }else{
                return true;
            }
        }
        return false;
    }
}

 

반응형

'LeetCode' 카테고리의 다른 글

1431. Kids With the Greatest Number of Candies  (0) 2023.11.01
443. String Compression  (0) 2023.10.30
547. Number of Provinces  (0) 2023.10.30
841. Keys and Rooms  (0) 2023.10.29
450. Delete Node in a BST  (0) 2023.10.29

관련글 더보기