[LeetCode] Minimum Operations to Collect Elements

아르당·4일 전

LeetCode

목록 보기
595/602
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

양의 정수 배열 nums와 정수 k가 주어진다.
한 번의 작업에, 배열의 마지막 요소를 제거하거나 컬렉션에 추가할 수 있다.
요소 1, 2, ..., k를 모으는 데 필요한 최소 연산 횟수를 반환해라.

Example

#1
Input: nums = [3, 1, 5, 4, 2], k = 2
Output: 4

#2
Input: nums = [3, 1, 5, 4, 2], k = 5
Output: 5

#3
Input: nums = [3, 2, 5, 3, 1], k = 3
Output: 4

Constraints

  • 1 <= nums.length <= 50
  • 1 <= nums[i] <= nums.length
  • 1 <= k <= nums.length
  • 입력값은 요소 1, 2, ..., k를 수집할 수 있도록 생성된다.

Solved

class Solution {
    public int minOperations(List<Integer> nums, int k) {
        boolean[] collected = new boolean[k + 1];
        int count = 0;

        for(int i = nums.size() - 1; i >= 0; i--){
            int num = nums.get(i);

            if(num <= k && !collected[num]){
                collected[num] = true;
                count++;
            }

            if(count == k){
                return nums.size() - i;
            }
        }

        return -1;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글