Skip to content

2460. Apply Operations to an Array 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  vector<int> applyOperations(vector<int>& nums) {
    vector<int> ans(nums.size());

    for (int i = 0; i + 1 < nums.size(); ++i)
      if (nums[i] == nums[i + 1]) {
        nums[i] *= 2;
        nums[i + 1] = 0;
      }

    int i = 0;
    for (const int num : nums)
      if (num > 0)
        ans[i++] = num;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int[] applyOperations(int[] nums) {
    int[] ans = new int[nums.length];

    for (int i = 0; i + 1 < nums.length; ++i)
      if (nums[i] == nums[i + 1]) {
        nums[i] *= 2;
        nums[i + 1] = 0;
      }

    int i = 0;
    for (final int num : nums)
      if (num > 0)
        ans[i++] = num;

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def applyOperations(self, nums: List[int]) -> List[int]:
    ans = [0] * len(nums)

    for i in range(len(nums) - 1):
      if nums[i] == nums[i + 1]:
        nums[i] *= 2
        nums[i + 1] = 0

    i = 0
    for num in nums:
      if num > 0:
        ans[i] = num
        i += 1

    return ans