26. Remove Duplicates from Sorted Array

26. Remove Duplicates from Sorted Array

题目

 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 by modifying the input array in-place with O(1) extra memory.

Example:

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

解析

  • 此题和在字符串中去掉某一元素类似str[j++]=str[i]
  • 此题说清楚了的,只是没有理解in-place算法意思
class Solution_26 {
public:
     
    // 此题没有说清楚,return 长度;但是nums要是去掉重复元素的
    int removeDuplicates(vector<int>& nums) {
        if (nums.size()<2)
        {
            return nums.size();
        }
        //int cnt = 0; 
        //int j = 0;
        //for (int i = 1; i < nums.size();)
        //{
        //  if (nums[j] == nums[i])
        //  {
        //      i++;
        //  }
        //  else  //没有去掉重复元素
        //  {
        //      cnt++;
        //      j = i;
        //      i++;
        //  }
        //}
        //return cnt+1;

        int cnt = 1;
        for (int i = 1; i < nums.size();i++)
        {
            if (nums[i]!=nums[i-1])
            {
                nums[cnt++] = nums[i];
            }
        }
        return cnt;
    }

    int removeDuplicates1(int A[], int n) {
        if (n<2)
        {
            return n;
        }
        int cnt = 1;
        for (int i = 1; i < n;i++)
        {
            if (A[i]!=A[i-1])
            {
                A[cnt++] = A[i];
            }
        }
        return cnt;
    }
};

题目来源

    原文作者:ranjiewen
    原文地址: https://www.cnblogs.com/ranjiewen/p/8340452.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞