C++ Remove Adjacent Array Duplicates

To remove adjacent duplicate items in an array, you can use two pointers to traverse the array and copy non-duplicate elements to a new array.

Here is an example code snippet:

#include <iostream>
#include <vector>

std::vector<int> removeAdjacentDuplicates(std::vector<int>& nums) {
    std::vector<int> result;
    
    int n = nums.size();
    if (n == 0) {
        return result;
    }
    
    result.push_back(nums[0]);
    
    for (int i = 1; i < n; i++) {
        if (nums[i] != nums[i - 1]) {
            result.push_back(nums[i]);
        }
    }
    
    return result;
}

int main() {
    std::vector<int> nums = {1, 2, 2, 3, 4, 4, 4, 5};
    
    std::vector<int> result = removeAdjacentDuplicates(nums);
    
    for (int num : result) {
        std::cout << num << " ";
    }
    
    return 0;
}

In the example above, the function removeAdjacentDuplicates is used to remove adjacent duplicate items from the input array nums, and it returns a new array without any duplicates. In the main function, the input array nums is first defined and the removeAdjacentDuplicates function is called. Finally, the array without duplicates is outputted.

bannerAds