Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 2460. Apply Operations to an Array

Rain Hu

2460. Apply Operations to an Array


一、題目

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:

Example 1:

Constraints:


二、分析

三、解題

1. Two Pointer

vector<int> applyOperations(vector<int>& nums) {
    for (int i = 0; i < nums.size()-1; i++) {
        if (nums[i] == 0) continue;
        if (nums[i] == nums[i+1]) {     // 將前後重複的數字加到前者
            nums[i] *= 2;
            nums[i+1] = 0;
        }
    }
    int i = 0, j = 0;
    while (i < nums.size()) {
        if (nums[i] != 0) {         // 將零全部移到後面
            nums[j++] = nums[i++];
        } else {
            i++;
        }
    }
    while (j < nums.size()) {
        nums[j++] = 0;
    }
    return nums;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2461. Maximum Sum of Distinct Subarrays With Length K
Next
[LeetCode] 1323. Maximum 69 Number