[关闭]
@CrazyHenry 2018-01-01T09:50:12.000000Z 字数 1841 阅读 1222

Leetcode80. Remove Duplicates from Sorted Array II

ddddLeetcode刷题


95874-106.jpg-1429.6kB

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. 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-80
  4. //T(n)=O(n), S(n)=O(1)
  5. class Solution {
  6. public:
  7. int removeDuplicates(vector<int>& nums) {
  8. if(nums.empty()) return 0;
  9. unsigned cnt = 0;
  10. int temp = nums[0];
  11. vector<int>::size_type index = 1;//decltype(nums.size()) index = 0;
  12. for(decltype(nums.size()) i = 1; i < nums.size(); i++)
  13. {
  14. if(nums[i] != temp)
  15. {
  16. cnt = 0;
  17. temp = nums[i];
  18. nums[index++] = nums[i];
  19. }
  20. else
  21. {
  22. ++cnt;
  23. if(cnt < 2)
  24. {
  25. nums[index++] = nums[i];
  26. }
  27. }
  28. }
  29. return index;
  30. }
  31. };

image.png-113.4kB

优秀代码1:

  1. class Solution
  2. {
  3. public:
  4. int removeDuplicates(vector<int>& nums)
  5. {
  6. const int n = nums.size();
  7. int index = 0;
  8. for (int i = 0; i < n; ++i)
  9. {
  10. if (i > 0 && i < n - 1 && nums[i] == nums[i - 1] && nums[i] == nums[i + 1])
  11. continue;
  12. nums[index++] = nums[i];
  13. }
  14. return index;
  15. }
  16. };

image.png-67.7kB

image.png-80.9kB

优秀代码2:

  1. class Solution
  2. {
  3. public:
  4. int removeDuplicates(vector<int>& nums)
  5. {
  6. if (nums.size() <= 2) return nums.size();
  7. int index = 2;
  8. for (int i = 2; i < nums.size(); i++)
  9. {
  10. if (nums[i] != nums[index - 2])//这里不能用nums[i - 2]
  11. nums[index++] = nums[i];
  12. }
  13. return index;
  14. }
  15. };

image.png-68.7kB

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