需求
在尾部插⼊、删除元素是⽐较⾼效的,时间复杂度 是 O(1),但是如果在中间或者开头插⼊、删除元素,就会涉及数据的搬移,时间复杂度为 O(N),效率较低。
代码
#include <stdio.h>// 相邻元素去重
int removeDuplicates(int* nums, int n){if (n == 0) return 0;int slow = 0, fast = 1;while (fast < n) {if (nums[fast] != nums[slow]) {slow++;// 维护 nums[0..slow] ⽆重复nums[slow] = nums[fast];}fast++;}// ⻓度为索引 + 1return slow + 1;}// 相同元素去重 setint toSet(int* nums, _Bool* flag, int n){if (n == 0) return 0;int slow = 0, fast = 1;while (fast < n) {int hashcode = nums[fast] % n;if (nums[fast] != nums[slow] && !flag[hashcode]) {flag[hashcode] = 1;slow++;// 维护 nums[0..slow] ⽆重复nums[slow] = nums[fast];}fast++;}// ⻓度为索引 + 1return slow + 1;}void main() {int a[10] = {1, 1, 2, 2, 1, 1, 3, 1, 2, 2};int size = removeDuplicates(a, 10);for(int i = 0; i < size; ++i)printf("%d ", a[i]);printf("\n ");_Bool flag[10] = {0}; size = toSet(a, flag, 10);for(int i = 0; i < size; ++i)printf("%d ", a[i]);}
输出
1 2 1 3 1 2 1 2 1 3
C双指针滑动窗口算法-CSDN博客