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

Given an array and a value, remove all instances of that value in place and return the new length.

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

 

思路:

因为可以改变元素顺序,所以只需要把最后端的非val元素用最前端的val代替即可,前后两个指针同时移动直到相遇。

AC代码:

 

 

 1 class Solution {
 2 public:
 3     int removeElement(vector<int>& nums, int val) {
 4         int i=0,n=nums.size()-1;
 5         if(n<0)
 6             return 0;
 7         while(nums[n]==val)
 8             n--;
 9         if(n<0)
10             return 0;
11         while(i<n){
12             while(nums[n]==val){
13                 n--;
14             }
15             if(i>n)
16                 break;
17             if(nums[i]==val){
18                 nums[i]=nums[n];
19                 n--;
20             }
21             i++;
22         }
23         while(nums[n]==val){
24                 n--;
25             }
26         return n+1;
27     }
28 };