LeetCode problem solving # 14: Remove the element

topic

Given an array nums and a value val, you need to place the elements to remove all equal values ​​val, and returns the new length of the array after removal.

Do not use extra space for an array, you must modify the input array in place and completed under the conditions of use O (1) extra space.

Order of the elements may be changed. You do not need to consider beyond the elements of the new array length behind.

Example 1:

给定 nums = [3,2,2,3], val = 3,

函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。

你不需要考虑数组中超出新长度后面的元素。

Example 2:

给定 nums = [0,1,2,2,3,0,4,2], val = 2,

函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。

注意这五个元素可为任意顺序。

你不需要考虑数组中超出新长度后面的元素。

Example 3:

给定 nums = [0,1,2,2,3,0,4,2], val = 2,

函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。

注意这五个元素可为任意顺序。

你不需要考虑数组中超出新长度后面的元素。

The first wording:

class Solution {
    public int removeElement(int[] nums, int val) {
        if (nums == null  || nums.length == 0){
            return 0;
        }

        int result = nums.length;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == val){
                result = result - 1;
            }
        }

        return result;
        
    }
}

The reason is that the failure to submit entitled asked to return the length of the new array, so you have to have a new array to produce the job. According to the wording of the first edition only to get the length, but there is no specified elements of the original array to delete, leading to fail.

After modifying the wording:

class Solution {
    public int removeElement(int[] nums, int val) {
        if (nums == null  || nums.length == 0){
            return 0;
        }

        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val){
                nums[result++] = nums[i];
            }
        }

        return result;
        
    }
}
Published 88 original articles · won praise 49 · Views 100,000 +

Guess you like

Origin blog.csdn.net/Diamond_Tao/article/details/102978713