LeetCode(27):Remove Element

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.

题意:从数组中移除所有的给定的某个值,并返回数组新的长度;最后一句的意思是在新的长度后面的元素是任意的,没有顺序的要求,只要是之前数组中的元素即可,后面的元素无所谓。

思路:采用两个指针left和right,left指向数组的第一个元素,right指向数组的最后一个元素。然后分别进行判断,对于left指针如果其指向的元素值等于指定的值,则用right指定的元素进行替代,前提是right指向的元素不等于指定的值,然left指向其相邻右边的元素,right指向其相邻的左边的元素;对于right指针,如果其指向的元素等于指定的值,则直接其指针指向相邻的左边的元素,否则不改变;直到left<=right。

代码:

public int removeElement(int[] nums, int val) {
       int left = 0,right = nums.length-1;
        while(left<=right){
            if(nums[left] == val)//如果left指向的值等于val
            {   
                if(nums[right]==val) //right指向的值如果也等于val
                { 
                    right=right - 1;   //right 指向相邻的左边的一个元素
                }
                else{
                 nums[left] = nums[right];  //将right指向的值替代为left指向的值
                 left += 1;                 //更新指针
                 right -= 1;                
             }
         }else  //否则,指向下一个元素
         {
             left += 1;
         }
    }
    return right+1;  //返回数组长度
        
    }

结果:

原文地址:https://www.cnblogs.com/Lewisr/p/5102163.html