删除有序数组中重复出现的元素

来源:互联网 发布:阿里云系统怎么样os 编辑:程序博客网 时间:2024/06/05 02:16

一起来看看这道题吧:

Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear onlyonce 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 nums = [1,1,2],

Your function should return length = 2, with the first two elements ofnums being 1 and 2 respectively. It doesn't matter what you leave beyond the new length.


这是取自LeetCode的一道题,题目大意是给你一个有序的数组,其中有些元素是重复的,且最多出现两次,现在让你写一个函数,把这个数组里重复的那些元素删除一个,留下一个,并返回新的元素个数。

那么这道题就很简单了,因为数组已经是是有序的,我们只需要遍历一遍,将多余的元素删除掉就好了。

接下来就直接贴上函数部分的实现:

int remove(int *arr, int sz){int i = 0;int index = 0;for (i = 1; i < sz; i++) {if (arr[index] != arr[i]) {//依次向后比较,若不相等,则用arr[i]覆盖arr[index+1],否则(遇到的是重复元素),i往后移arr[++index] = arr[i];//当index与i之间没有其他元素,index + 1 就是i哦,相当于index后移,但是值没改变}//当index与i之间有其他元素,那么这些元素必定是重复得了,直接覆盖掉}return index + 1;}
要是还看不太明白的话,画个图看看吧大笑




1 0
原创粉丝点击