java.lang.Object
g2401_2500.s2460_apply_operations_to_an_array.Solution

public class Solution extends Object
2460 - Apply Operations to an Array.<p>Easy</p> <p>You are given a <strong>0-indexed</strong> array <code>nums</code> of size <code>n</code> consisting of <strong>non-negative</strong> integers.</p> <p>You need to apply <code>n - 1</code> operations to this array where, in the <code>i<sup>th</sup></code> operation ( <strong>0-indexed</strong> ), you will apply the following on the <code>i<sup>th</sup></code> element of <code>nums</code>:</p> <ul> <li>If <code>nums[i] == nums[i + 1]</code>, then multiply <code>nums[i]</code> by <code>2</code> and set <code>nums[i + 1]</code> to <code>0</code>. Otherwise, you skip this operation.</li> </ul> <p>After performing <strong>all</strong> the operations, <strong>shift</strong> all the <code>0</code>&rsquo;s to the <strong>end</strong> of the array.</p> <ul> <li>For example, the array <code>[1,0,2,0,0,1]</code> after shifting all its <code>0</code>&rsquo;s to the end, is <code>[1,2,1,0,0,0]</code>.</li> </ul> <p>Return <em>the resulting array</em>.</p> <p><strong>Note</strong> that the operations are applied <strong>sequentially</strong> , not all at once.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> nums = [1,2,2,1,1,0]</p> <p><strong>Output:</strong> [1,4,2,0,0,0]</p> <p><strong>Explanation:</strong> We do the following operations:</p> <ul> <li> <p>i = 0: nums[0] and nums[1] are not equal, so we skip this operation.</p> </li> <li> <p>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, <strong><ins>4</ins></strong> , <strong><ins>0</ins></strong> ,1,1,0].</p> </li> <li> <p>i = 2: nums[2] and nums[3] are not equal, so we skip this operation.</p> </li> <li> <p>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, <strong><ins>2</ins></strong> , <strong><ins>0</ins></strong> ,0].</p> </li> <li> <p>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, <strong><ins>0</ins></strong> , <strong><ins>0</ins></strong> ].</p> </li> </ul> <p>After that, we shift the 0&rsquo;s to the end, which gives the array [1,4,2,0,0,0].</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> nums = [0,1]</p> <p><strong>Output:</strong> [1,0]</p> <p><strong>Explanation:</strong> No operation can be applied, we just shift the 0 to the end.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>2 <= nums.length <= 2000</code></li> <li><code>0 <= nums[i] <= 1000</code></li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • applyOperations

      public int[] applyOperations(int[] nums)