删除所有相邻的重复元素
[!Tip]
本节源代码见Github链接🔗
问题描述
给定一个数字数组,删除相邻的重复数字,结果数组中不能有任何相邻的重复数字。示例如下:
输入:1,5,6,8,8,8,0,1,1,0,6,5;输出:1
输入:1,9,6,8,8,8,0,1,1,0,6,5;输出:1,9,5
核心思路
用“就地栈”,当栈中元素与当前数字不相等时,就将当前数字入栈,否则跳过该数字,直到找到与栈顶元素不相等的数字,并从栈中删除该元素。
实现代码
【👉🏻>>点击展开查看代码】
/**
* 删除栈中重复的数字
*
* @className: RemoveAdjacentDuplicates
* @author: Max Solider
* @date: 2023-06-10 09:04
*/public class RemoveAdjacentDuplicates {
public static int removeAdjacentDuplicates(int[] array) {
int stkptr = -1;
int i = 0;
while (i < array.length) {
if (stkptr == -1 || array[stkptr] != array[i]) {
stkptr++;
array[stkptr] = array[i];
i++;
} else {
while (i < array.length && array[stkptr] == array[i]) {
i++;
}
stkptr--;
}
}
return stkptr;
}
public static void main(String[] args) {
int[] array = new int[]{1, 3, 4, 2, 3, 3, 2, 5,4, 4, 5};
int ptr = removeAdjacentDuplicates(array);
for (int i = 0; i
时间复杂度
时间复杂度为O(n),用于扫描长度为n的数组。
空间复杂度
空间复杂度为O(n),用于存储栈空间。