LeetCode-in-Java

3834. Merge Adjacent Equal Elements

Medium

You are given an integer array nums.

You must repeatedly apply the following merge operation until no more changes can be made:

After each merge operation, the array size decreases by 1. Repeat the process on the updated array until no more changes can be made.

Return the final array after all possible merge operations.

Example 1:

Input: nums = [3,1,1,2]

Output: [3,4]

Explanation:

Example 2:

Input: nums = [2,2,4]

Output: [8]

Explanation:

Example 3:

Input: nums = [3,7,5]

Output: [3,7,5]

Explanation:

There are no adjacent equal elements in the array, so no operations are performed.

Constraints:

Solution

public class Solution {
    public java.util.List<Long> mergeAdjacent(int[] nums) {
        java.util.List<Long> ans = new java.util.ArrayList<>();
        for (long num : nums) {
            long curr = num;
            while (!ans.isEmpty() && ans.get(ans.size() - 1) == curr) {
                ans.remove(ans.size() - 1);
                curr *= 2;
            }
            ans.add(curr);
        }
        return ans;
    }
}