[Leetcode] Remove Element

来源:互联网 发布:python宝典 pdf 编辑:程序博客网 时间:2024/06/05 19:33

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.

用index1记录从左边数第一个value的位置,index2记录从右边起第一个不是value的位置,然后两个数交换,循环,直到index2<=index1说明交换结束。最后返回index1。

public class Solution {    public int removeElement(int[] nums, int val) {        int len=nums.length;        if(len==0) return 0;        int index1=0,index2=len-1;        while(index1<len)        {            if(nums[index1]!=val)             {              index1++;                continue;              }            while((index2>index1)&&(nums[index2]==val)) index2--;            if(index2<=index1) break;            else            {                nums[index1]=nums[index2];                nums[index2]=val;            }            index1++;        }        return index1;    }}



0 0