Input: nums = [1,2,3,4,2,3,3,5,7]
Output: 2
Explanation:
In the first operation, the first 3 elements are removed, resulting in the array [4, 2, 3, 3, 5, 7].
In the second operation, the next 3 elements are removed, resulting in the array [3, 5, 7], which has distinct elements.
Therefore, the answer is 2.
입력: nums = [1,2,3,4,2,3,3,5,7]
출력: 2
설명:
첫 번째 연산에서 앞의 3개의 요소가 제거되어 배열이 [4, 2, 3, 3, 5, 7]이 됩니다.
두 번째 연산에서 다음 3개의 요소가 제거되어 배열이 [3, 5, 7]이 됩니다. 이 배열은 모든 요소가 서로 다릅니다.
따라서 정답은 2입니다.
Input: nums = [4,5,6,4,4]
Output: 2
Explanation:
In the first operation, the first 3 elements are removed, resulting in the array [4, 4].
In the second operation, all remaining elements are removed, resulting in an empty array.
Therefore, the answer is 2.
입력: nums = [4,5,6,4,4]
출력: 2
설명:
첫 번째 연산에서 앞의 3개의 요소가 제거되어 배열이 [4, 4]이 됩니다.
두 번째 연산에서 남은 모든 요소가 제거되어 배열이 비게 됩니다.
따라서 정답은 2입니다.
Input: nums = [6,7,8,9]
Output: 0
Explanation:
The array already contains distinct elements. Therefore, the answer is 0.
입력: nums = [6,7,8,9]
출력: 0
설명:
이 배열은 이미 모든 요소가 서로 다릅니다.
따라서 아무런 연산 없이도 조건을 만족하므로 정답은 0입니다.
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
from collections import deque
from typing import List
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
count = 0
numQueue = deque(nums)
while len(numQueue) > 0:
if len(set(numQueue)) == len(numQueue):
return count
for _ in range(min(3,len(numQueue))):
numQueue.popleft()
count += 1
return count
여기서 중요한 로직은
if len(set(numQueue)) == len(numQueue):
return count
for _ in range(min(3,len(numQueue))):
numQueue.popleft()
이 부분이다.
어떻게 길이로 중복을 확인하는지 궁금할텐데 과정은 이렇다.
첫번째 testcase인 nums = [1,2,3,4,2,3,3,5,7]이것으로 예시를 들어보겠다.
set(numQueue) = {1, 2, 3, 4, 5, 7} (중복 제거)len(numQueue) = 9len(set(numQueue)) = 6-> 첫 3개 제거
numQueue → [4, 2, 3, 3, 5, 7]count = 1set(numQueue) = {2, 3, 4, 5, 7} (중복 제거)len(numQueue) = 6len(set(numQueue)) = 5-> 첫 3개 제거
numQueue → [3, 5, 7]count = 2set(numQueue) = {3, 5, 7} (중복 제거)
len(numQueue) = 3
len(set(numQueue)) = 3
➡️서로 같다 -> 중복 없음
반복 종료, return count = 2
이런식으로 길이를 비교해서도 중복 유무를 비교할 수 있다.