[leetcode](Remove Duplicates from Sorted Array II C语言实现)

来源:互联网 发布:常用单片机型号 编辑:程序博客网 时间:2024/05/16 14:05

Remove Duplicates from Sorted Array II
Follow up for “Remove Duplicates”:
What if duplicates are allowed at most twice?

For example,
Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].
题意:把数组中重复数值个数大于2个的数值删除掉。
解题思路:循环遍历整个数组,当判断重复数为m,并m>2时,把后面的数组向前移动n-2位。

实现C代码如下:

/** * 解题思路:判断重复的个数,当大于2个值的个数为i时,让后面的数往前面移动i-2位,并重新让n=i-2 */int removeDuplicates(int A[], int n) {    int i,j,m,x;    for(i = 0; i< n-1; i++){        if(A[i] == A[i+1]){            i++;            j = i;//存储临时变量,用于后面i是否大于j的判断            while(i < n-1 && A[i] == A[i+1]){                i++;            }            x=i;            for(m=j+1;j<i && i<n-1;m++){//若i>j说明,重复个数大于2个,并把后面的数往前面移动x-j个位置                A[m] = A[i+1];i++;            }            n=n-(x-j);//重新调整n的大小            i = j;//重新调整i的值        }    }    return n;}
0 0
原创粉丝点击