[关闭]
@CrazyHenry 2018-01-01T09:51:09.000000Z 字数 2359 阅读 1606

Leetcode26. Remove Duplicates from Sorted Array

ddddLeetcode刷题


354634-106.jpg-704.7kB

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.

首先,是我的代码,基于新标准编码原则:

  1. //Author: Li-Yingmin@https://liyingmin.wixsite.com/henry
  2. //Email: li_yingmin@outlook.com
  3. //Leetcode-26
  4. //T(n)=O(n), S(n)=O(1)
  5. class Solution {
  6. public:
  7. int removeDuplicates(vector<int>& nums) {
  8. if(0 == nums.size())
  9. return 0;
  10. auto vbeg = nums.begin();
  11. auto vend = nums.end();
  12. auto temp = *vbeg; //若nums为空,执行此操作是未定义的
  13. ++vbeg;
  14. for ( ; vbeg != vend; ++vbeg)
  15. {
  16. if(*vbeg == temp)
  17. {
  18. nums.erase(vbeg);
  19. --vbeg;
  20. vend = nums.end();
  21. }
  22. else temp = *vbeg;
  23. }
  24. return nums.size();
  25. }
  26. };

image.png-115.1kB

主要是使用了STL里的erase()操作来删除元素,有几点需要注意:

优秀代码1:

  1. /*
  2. * LeetCode, Remove Duplicates from Sorted Array
  3. * 时间复杂度O(n),空间复杂度O(1)
  4. */
  5. class Solution {
  6. public:
  7. int removeDuplicates( vector<int> & nums )
  8. {
  9. if ( nums.empty() )
  10. return(0);
  11. int index = 0;
  12. for ( int i = 1; i < nums.size(); i++ )
  13. {
  14. if ( nums[index] != nums[i] )
  15. nums[++index] = nums[i];
  16. }
  17. return(index + 1);
  18. }
  19. };

image.png-75.2kB

优秀代码2:

  1. class Solution {
  2. public:
  3. int removeDuplicates( vector<int> & nums )
  4. {
  5. return(distance( nums.begin(), removeDuplicates( nums.begin(), nums.end(), nums.begin() ) ) );
  6. }
  7. template<typename InIt, typename OutIt>//相当于对unique的一种实现方式
  8. OutIt removeDuplicates( InIt first, InIt last, OutIt output )
  9. {
  10. while ( first != last )
  11. {
  12. *output++ = *first;
  13. first = upper_bound( first, last, *first );
  14. }
  15. return(output);
  16. }
  17. };

image.png-114.4kB

优秀代码3:使用STL一步完成

  1. class Solution
  2. {
  3. public:
  4. int removeDuplicates( vector<int> & nums )
  5. {
  6. return(distance( nums.begin(), unique( nums.begin(), nums.end() ) ) );
  7. }
  8. };

image.png-47.1kB

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注