【27】Remove Element

来源:互联网 发布:百度知道与知乎 编辑:程序博客网 时间:2024/04/29 06:07

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 in place with constant memory.

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

Example:
Given input array nums = [3,2,2,3], val = 3

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


其实就是把要删掉的数字放到后面,把留下的数字放到前面。设两个标记i和j,i从前往后走,j从后往前走,每次i找到一个等于val的数,j找到一个不等于val的数,然后交换i和j指向的两个数,直到i和j相遇。因为这里不需要保留被删掉的数,所以交换可以变为赋值,即把j指向的数赋值给i指向的数。这个过程类似于快排时每一趟的处理。
int removeElement(vector<int>& nums, int val) {    int n=nums.size();    if(n==0)return 0;    int i=0,j=n-1;    while(nums[j]==val)j--;    while(i<=j){        if(nums[i]==val){            nums[i]=nums[j];            i++;            j--;            while(i<=j && nums[j]==val)j--;        }        else i++;    }            return j+1;}

0 0
原创粉丝点击