[LeetCode] Apply Operations to an Array

준규·2023년 2월 6일
0

1.문제


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 multiply nums[i] by 2 and set nums[i + 1] to 0. 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 its 0'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.


index 가 0부터 시작하는 정수 배열 nums가 주어질 때 nums[i] === nums[i+1] 이면 nums[i]는 2를 곱하고, nums[i+1]은 0으로 만드는 연산을 한다. (만약 다르다면 skip) 연산을 끝까지 한 후 0인 숫자는 배열의 마지막으로 뺀 배열을 리턴하는 문제이다.


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

2.풀이

  1. nums를 순회하면서 operation을 수행한다.
  2. nums 중 0인 숫자를 빼서 다른 배열에 저장한다.
  3. nums와 다른배열을 합쳐서 리턴한다.

/**
 * @param {number[]} nums
 * @return {number[]}
 */
const applyOperations = function (nums) {
  // nums를 순회하면서 operation 수행
  for (let i = 0; i < nums.length - 1; i++) {
    if (nums[i] === nums[i + 1]) {
      nums[i] = nums[i] * 2;
      nums[i + 1] = 0;
    }
  }

  const zeros = [];

  // nums에서 0인 숫자를 zeros에 저장한다.
  for (let i = 0; i < nums.length; i++) {
    if (nums[i] === 0) {
      const temp = nums.splice(i, 1);
      zeros.push(temp);
      i--;
    }
  }

  // nums와 zeros를 합쳐서 리턴한다.
  return nums.concat(zeros);
};

3.결과

profile
안녕하세요 :)

0개의 댓글