27. Remove Element

Description:

https://leetcode.com/problems/remove-element/#/description

Boundary:

  • nums.size() = 0  return 0
  • val > maximum  return nums.size()
  • if cannot find return nums.size()

Algorithm:

  1. sort
  2. go through array and find the beginning index and end index of the val
  3. nums.erase()

Code:

class Solution {
public:
int removeElement(vector<int>& nums, int val) {
if (nums.size() == 0) return 0;
sort(nums.begin(), nums.end());
if (val > nums[nums.size() – 1]) return nums.size();

int beginner = -1, ender = -1;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == val)
{
beginner = i;
ender = i;
while (i + 1 < nums.size() && nums[i] == nums[i + 1])
{
i++;
ender++;
}
break;
}
}
if (ender > -1)
nums.erase(nums.begin() + beginner, nums.begin() + ender + 1);
return nums.size();
}
};

Timing:

O(n)

Leave a Reply

Your email address will not be published. Required fields are marked *