【26】Remove Duplicates from Sorted Array

来源:互联网 发布:最新股市交易软件下载 编辑:程序博客网 时间:2024/05/19 03:20

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两个标记,i表示当前不重复数组的结尾位置,j表示当前处理到的位置,若j处出现一个与之前不同的数,就把它放到i处,并让i++
int removeDuplicates(vector<int>& nums) {    int n=nums.size();    if(n==0)return 0;    int i,j;    for(i=1,j=1;j<n;j++){      if(nums[j]!=nums[j-1]){        nums[i]=nums[j];        i++;      }    }    return i;}

0 0