[关闭]
@CrazyHenry 2018-01-03T18:32:24.000000Z 字数 1366 阅读 1118

Leetcode27. Remove Element

ddddLeetcode刷题


102239-106.jpg-309.4kB

Given an array and a value, remove all instances of that value in-place 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.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example:

  1. Given nums = [3,2,2,3], val = 3,
  2. Your function should return length = 2, with the first two elements of nums being 2.

说明:

In computer science, an in-place algorithm is an algorithm which transforms input using no auxiliary data structure.

我的代码1:

  1. //Author: Li_Yingmin@https://liyingmin.wixsite.com/henry
  2. //Email: li_yingmin@outlook DOT com
  3. //Leetcode-27
  4. //T(n)=O(n), S(n)=O(1)
  5. class Solution {
  6. public:
  7. int removeElement(vector<int>& nums, int val) {
  8. if(nums.size()<1) return 0;
  9. for(auto it = nums.begin(); it != nums.end(); ++it)
  10. {
  11. if(*it == val)
  12. {
  13. nums.erase(it);
  14. --it;
  15. }
  16. }
  17. return nums.size();
  18. }
  19. };

优秀代码1:

  1. // LeetCode, Remove Element
  2. // T(n)=O(n),S(n)=O(1)
  3. class Soluntion
  4. {
  5. public:
  6. int removeElement(vector<int>& nums, int val)
  7. {
  8. return distance(nums.begin(), remove(nums.begin(), nums.end(), val));
  9. }
  10. };

image.png-85.8kB

优秀代码2:

  1. class Solution
  2. {
  3. public:
  4. int removeElement(vector<int>& nums, int target)
  5. {
  6. int index = 0;
  7. for (int i = 0; i < nums.size(); ++i)
  8. {
  9. if (nums[i] != target)
  10. {
  11. nums[index++] = nums[i];
  12. }
  13. }
  14. return index;
  15. }
  16. };
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注