- 82. Remove Duplicates from Sorte
- 线性表-Remove Duplicates from Sorte
- 线性表-Remove Duplicates from Sorte
- 线性表-Remove Duplicates from Sorte
- 026,Remove Duplicates from Sorte
- 082 Remove Duplicates from Sorte
- 26 Remove Duplicates from Sorte
- 80. Remove Duplicates from Sorte
- 83. Remove Duplicates from Sorte
- 26. Remove Duplicates from Sorte
题目
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;
}
网友评论