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 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:

Given nums = [3,2,2,3], val = 3,

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

 

从一个数组中删除指定元素,而且也只能在当前数组中操作。这跟Remove Duplicates from Sorted Array一样的要求,所以思路也差不多。就是用两个指针,一个用于遍历,一个代表新数组添加元素。这题比去除重复元素那题要简单。

 

class Solution {
    public int removeElement(int[] nums, int val) {
        if(nums==null||nums.length==0)
            return 0;
        int count=0;//该指针用于添加元素,i用于遍历数组
        for(int i=0;i<nums.length;i++){
            if(nums[i]!=val)
                nums[count++]=nums[i];
        }
        return count;
    }
}

 


 
                    
            
                

相关文章:

  • 2021-09-27
  • 2021-03-31
  • 2021-12-06
  • 2021-06-27
  • 2021-12-29
  • 2022-03-01
  • 2021-07-07
猜你喜欢
  • 2021-06-15
相关资源
相似解决方案