Leetcode (Java) -27. Removing elements

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:

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

Function should return a new length of 2, and the first two elements nums are 2.

You do not need to consider beyond the elements of the new array length behind.
Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

New function should return the length 5 and the first five elements nums is 0, 1, 3, 0, 4.

Note that these five elements can be in any order.

You do not need to consider beyond the elements of the new array length behind.
Description:

Why return value is an integer, but the answer is an array of output it?

Please note that the input array is passed by "reference" mode, which means to modify the input array is visible to the caller within the function.

You can imagine the internal operation is as follows:

// nums is a "reference" passed by. That is, any copy right argument
int len = removeElement (nums, val );

// modify the input array in a function and the caller is visible.
// The length of your function returns, it will print out all elements of the array length range.
for (int I = 0; I <len; I ++) {
    Print (the nums [I]);
}

 

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

 

发布了255 篇原创文章 · 获赞 35 · 访问量 2万+

Guess you like

Origin blog.csdn.net/qq_38905818/article/details/104616380