난이도: Easy
Problem Description
You are given a 0-indexed array nums
of size n
consisting of non-negative integers.
You need to apply n - 1
operations to this array where, in the ith
operation (0-indexed), you will apply the following on the ith
element of nums
:
- If
nums[i] == nums[i + 1]
, then multiplynums[i]
by2
and setnums[i + 1]
to0
. Otherwise, you skip this operation.
After performing all the operations, shift all the 0
's to the end of the array.
- For example, the array
[1,0,2,0,0,1]
after shifting all its0
's to the end, is[1,2,1,0,0,0]
.
Return the resulting array.
Note that the operations are applied sequentially, not all at once.
Problem Example
Example 1:
Input: nums = [1,2,2,1,1,0]
Output: [1,4,2,0,0,0]
Explanation: We do the following operations:
- i = 0: nums[0] and nums[1] are not equal, so we skip this operation.
- i = 1: nums[1] and nums[2] are equal, we multiply nums[1] by 2 and change nums[2] to 0. The array becomes [1,4,0,1,1,0].
- i = 2: nums[2] and nums[3] are not equal, so we skip this operation.
- i = 3: nums[3] and nums[4] are equal, we multiply nums[3] by 2 and change nums[4] to 0. The array becomes [1,4,0,2,0,0].
- i = 4: nums[4] and nums[5] are equal, we multiply nums[4] by 2 and change nums[5] to 0. The array becomes [1,4,0,2,0,0].
After that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0].
Example 2:
Input: nums = [0,1]
Output: [1,0]
Explanation: No operation can be applied, we just shift the 0 to the end.
Constraints
2 <= nums.length <= 2000
0 <= nums[i] <= 1000
✏️ Solution
class Solution:
def applyOperations(self, nums: List[int]) -> List[int]:
n = len(nums)
answer = []
for i in range(n):
if i+1 < n and nums[i] == nums[i+1]:
nums[i] *= 2
nums[i+1] = 0
if nums[i] != 0:
answer.append(nums[i])
for _ in range(n-len(answer)):
answer.append(0)
return answer
문제에서 주어진대로 `nums`의 요소들을 확인하여 `nums[i] == nums[i+1]`이면 `nums[i]`에 2를 곱하고 `nums[i+1]`은 0으로 만들어 주었다.
이후 현재 `nums[i]`가 0이 아니면 `answer` 리스트에 추가해주었다.
이렇게 하면 모든 요소를 확인했을 때, `answer`에는 0이 아닌 요소들만 들어가 있다.
예를 들어 `nums`가 [1,0,2,0,0,1]이라고 한다면 `answer`에는 [1,2,1]로 채워진다.
이제 nums의 길이 - answer의 길이 만큼 0을 answer에 채워주면 된다.
마지막에는 answer를 return 하고 정답을 맞을 수 있었다.
⚙️ Runtime & Memory
문제: 2460. Apply Operations to an Array
깃허브: github
algorithmPractice/LeetCode/2551-apply-operations-to-an-array at main · laewonJeong/algorithmPractice
하루 한 문제 챌린지. Contribute to laewonJeong/algorithmPractice development by creating an account on GitHub.
github.com
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 2161. Partition Array According to Given Pivot (Python) (0) | 2025.03.03 |
---|---|
[LeetCode] 2570. Merge Two 2D Arrays by Summing Values (Python) (0) | 2025.03.02 |
[LeetCode] 1092. Shortest Common Supersequence (Python) (0) | 2025.02.28 |
[LeetCode] 873. Length of Longest Fibonacci Subsequence (Python) (0) | 2025.02.27 |
[LeetCode] 1749. Maximum Absolute Sum of Any Subarray (Python) (0) | 2025.02.26 |