每日一题6.27

问题:

Given an array nums and a value val, 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.

删除数组中给定的数字。并返回新的长度。

思路:个人感觉设置一个标志位即可。我们不需要关心数组内元素是什么内容,只需要确定好具体长度即可。

class Solution {
    public int removeElement(int[] nums, int val) {
        if(nums.length==0)
            return 0;
       // if(val==null)return nums.length;
        int i=0;
        for(int n:nums)
        {
            if(n!=val)
            {
                nums[i++]=n;
            }
        }
        return i;
    }
}

猜你喜欢

转载自blog.csdn.net/q_all_is_well/article/details/80871211