One java written test every day2020-9-22

One java written test every day2020-9-22

leetCode 27. Remove elements

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

Do not use extra space for an array, you must use only (1) extra space and O -situ modify the input array .

The order of the elements can be changed. You don't need to consider the elements in the array beyond the new length.

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。

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

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

Description:

Why is the returned value an integer, but the output answer is an array?

Please note that the input array is passed in **"reference"**, which means that the modification of the input array in the function is visible to the caller.

You can imagine the internal operation as follows:

// nums 是以“引用”方式传递的。也就是说,不对实参作任何拷贝
int len = removeElement(nums, val);

// 在函数里修改输入数组对于调用者是可见的。
// 根据你的函数返回的长度, 它会打印出数组中 该长度范围内 的所有元素。
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

It is similar to the question yesterday

Use the pointer method:

public class 移除元素 {
    
    

    public static void main(String[] args) {
    
    
        System.out.println(removeElement(new int[]{
    
    3,2,2,3},3));
//        removeElement(new int[]{0,1,2,2,3,0,4,2},2);
    }

    public static 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;
    }
}

The time complexity is O(n)

The space complexity is O(1)

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_37924905/article/details/108741162