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.




class Solution {
public:
    int removeElement(vector<int>& nums, int val) {
        int low = 0;
        int high = 0;
        while(high < nums.size()) {
            if(nums[high] != val) {
                nums[low] = nums[high];
                low++;
            } 
            high++; 
        }
        return low;
    }
};

 













法1:

统计出val的数量,把val 交换到后面。

 1 class Solution {
 2     public int removeElement(int[] nums, int val) {
 3         int i = 0;
 4         int j = nums.length-1;
 5         int cnt = 0;
 6         for(int k =0;k<nums.length;k++)
 7             if(nums[k]==val)
 8                 cnt++;
 9         if(cnt==0)
10             return nums.length;
11         while(i<nums.length-cnt||j>nums.length-cnt){
12             while(i<nums.length-cnt&&nums[i]!=val) i++;
13             while(j>nums.length-cnt&&nums[j]==val) j--;
14             swap(nums,j,i);
15         }
16         return nums.length-cnt;
17     }
18     private void swap(int[] a,int i ,int j){
19         int t = a[i];
20         a[i] = a[j];
21         a[j] =t;
22     }
23 }

 


 1 class Solution {
 2     public int removeElement(int[] nums, int val) {
 3         int m = 0;
 4         for(int i = 0;i<nums.length;i++){
 5             if(nums[i]!=val){
 6                 nums[m] = nums[i];
 7                 m++;
 8             }
 9         }
10         return m;
11     }
12 }

 

posted @ 2018-05-07 16:37  乐乐章  阅读(165)  评论(0编辑  收藏  举报