Remove Duplicates from Sorted Array

来源:互联网 发布:淘宝购物津贴有什么用 编辑:程序博客网 时间:2024/06/03 17:39

Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

#include<stdio.h>int removeDuplicates(int A[],int length){    if(length == 0){        return 0;    }    int count = 1;    for(int i = 1; i < length; i++){        if(A[i] == A[i - 1]){            continue;                   }else{            A[count] = A[i];            count++;            }    }    for(int i = count; i < length; i++){        A[i] = 0x0;     }    printf("A[] = ");    for(int i = 0; i < count; i++){        printf("%d ",A[i]);    }    printf("\n");    return count;   }int main(){    int A[] = {1,1,2};    int length = sizeof(A)/sizeof(A[0]);    int count;    count = removeDuplicates(A,length);    printf("count = ");    printf("%d\n",count);    return 0;}

运行结果如图:
这里写图片描述

原创粉丝点击