leetcode 80 Remove Duplicates from Sorted Array II

来源:互联网 发布:c语言pthread 编辑:程序博客网 时间:2024/06/06 05:21

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 nums = [1,1,2],

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

在一个排序好的数组里面,删除里面重复的元素。
思路:设两个变量,i,j。
对于一个排序号的数组,A[N+1]>=A[N]
假设现在i=j+1;
如果A[i]==A[j],递增i,直到if(A[i]!=A[j]) ,然后A[j+1]=A[i]交换元素,j=0不能交换,因为只是删除重复的元素。
然后同时递增i,j;

int removeDuplicates(int* nums, int numsSize) {    if(numsSize==0)    {        return 0;    }    int j=0;    for(int i=1;i<numsSize;i++)    {        if(nums[j]!=nums[i])        {            nums[j+1]=nums[i];            j+=1;          }    }    return j+1;}
0 0
原创粉丝点击