[leedcode 27] 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.

public class Solution {
    public int removeElement(int[] nums, int val) {
        //此题非常简单,注意不允许占用额外空间,因此保留一个指针,指针index前面的数都不是给定的值,
        //因为index<=i,所以此思想成立
        int index=0;
        for(int i=0;i<nums.length;i++){
            if(nums[i]==val){
                continue;
            }else{
                nums[index++]=nums[i];
            }
            
        }
        return index;
    }
}

 

你可能感兴趣的:(element)