美文网首页
线性表-Remove Duplicates from Sorte

线性表-Remove Duplicates from Sorte

作者: faterman | 来源:发表于2018-12-18 10:49 被阅读6次

题目

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].

分析

为了不开辟新的空间,所以只在原来的数组里操作,并返回数组个数,所以用一个index下标来记录不重复数组长度,循环遍历i,并且在不相等的时候用,i来替换index,其实index是上次出现重复的位置。

实现

#include <stdio.h>

int removeDuplicates(int arr[], int size);

int main(int argc, const char * argv[]) {
    int arr[4] = {1, 1, 2, 3};
    int length = removeDuplicates(arr, 4);
    printf("the result length is %d\n", length);
    return 0;
}

int removeDuplicates(int arr[], int size) {
    
    int index = 1;
    
    for (int i = 1; i < size; i++) {
        if (arr[i] != arr[index-1]) {
            arr[index++] = arr[i];
        }
    }
    
    return index;
}

相关文章

网友评论

      本文标题:线性表-Remove Duplicates from Sorte

      本文链接:https://www.haomeiwen.com/subject/wxukkqtx.html