每个元素只能出现一次或两次。
Example 1: Given nums = [1, 1, 1, 2, 2, 3, 3, 3] The function should return 6, because [1, 1, 2, 2, 3, 3]. As each element can appear 上 ly twice.
解决方案很简单。
我们将有2个变量,国彩网将保存新的长度,另国彩网用于迭代数组。
由于最多允许2个重复项,因此我们将第三个元素向后移2个元素。如果元素相同,则存在重复3次的元素。
If if array[iter] == array [len-2], then array [iter]== array [len-2]== array [len-1]
下面是伪代码:
while (iterator < array_len) { if (array[iterator] != array[new_len-2]) { array[new_len++] = array[iterator]; } iterator++; }
我们将借助国彩网示例来理解该算法:
输入:[1、1、1、2、2、3]
pass = 1 Initial array = 1 1 1 2 2 3 iterator = 2 new_len = 2 if (array[iterator] != array[new_len-2]) if (1 != 1) false Hence iterator++ final array after pass 1 = 1 1 1 2 2 3
pass = 2 iterator = 3 new_len = 2 Initial array = 1 1 1 2 2 3 if (array[iterator] != array[new_len-2]) if (2 != 1) true then array[new_len++] = array[iterator]; iterator++ final array after pass 2 = 1 1 2 2 2 3
pass = 3 iterator = 4 new_len = 3 Initial array = 1 1 2 2 2 3 id (array[iterator] != array[new_len-2]) if (2 != 1) true then array[new_len++] = array[iterator]; iterator++ final array after pass 3 = 1 1 2 2 2 3
pass = 4 iterator = 5 new_len = 4 if (array[iterator] != array[new_len-2]) if (3 != 2) true then array[new_len++] = array[iterator]; iterator++ final array after pass 4 = 1 1 2 2 3 3 iterator = 5. Hence the result
C ++解决方案
#include<iostream> #include<vector> using namespace std; int removeDuplicates(int array[], int array_len) { // If the array len is less than or equal to 2 then no need to search for duplicate if (array_len <= 2) { return array_len; } // as we are allowed up to 2 duplicates, we start from the third element. // then we check the third element with the element 2 steps before it. If it is same, // it means it is the 3rd duplicate element. int new_len = 2; int iterator = 2; while (iterator < array_len) { if (array[iterator] != array[new_len-2]) { array[new_len++] = array[iterator]; } iterator++; } return new_len; } int main() { int arr[] = {1, 1, 1, 2, 2, 3}; int array_len = 6; int result = removeDuplicates(arr, array_len); cout<<"The length of the array after the duplicates are removed = "<< result <<endl; }
输出:
The length of the array after the duplicates are removed = 5
该网站上可用的教程列表:
C编程20+章 | C ++编程80+章 |
100多个编码问题 | 数据结构和算法85+章 |
系统设计20+章 | Shell脚本编写12章 |
4g LTE 60+章节 | 最常见的编码问题 |
5G NR 50+章 | Linux系统编程20+章 |