leetcode 27. Remove Element

Given an array nums and a value val, 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,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

题目大意:给定一个数组,一个值,返回删除数组中与这个值相等的元素后的数组的长度。要求:实现in-place操作,不另外新开辟空间

思路一:双指针。

1 int removeElement(vector<int>& nums, int val) {
2         int i = 0;
3         for (auto num : nums) {
4             if (num != val) {
5                 nums[i++] = num;
6             }
7         }
8         return i;
9     }

思路二:双指针,一头一尾, 类似快排,左指针直到指向等于val的索引为止,右指针直到指向不等于val的索引为止。

 1 int removeElement(vector<int> &nums, int val) {
 2         int i = 0, j = nums.size();
 3         while (i < j) {
 4             while ((i < j) && nums[i] != val) ++i;
 5             while ((i < j) && nums[j - 1] == val) --j;
 6             if (i < j)
 7                 swap(nums[i], nums[j - 1]);
 8         }
 9         return i;
10     }
原文地址:https://www.cnblogs.com/qinduanyinghua/p/11840058.html