每日一恋 - LeetCode 27. Remove Element(删除排序数组中的重复项)

题目描述:

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.

Example 1:

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

Your function should return length = 2, with the first two elements of nums being 2.

It doesn't matter what you leave beyond the returned length.

Example 2:

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

Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.

Note that the order of those five elements can be arbitrary.

It doesn't matter what values are set beyond the returned length.

给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。

不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。

元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

示例 1:

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

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

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

示例 2:

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

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

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

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

解法一(My Solution):

这题较容易,与LeetCode 26号题非常类似,每日一恋 - LeetCode 26. Remove Duplicates from Sorted Array(删除排序数组中的重复项)

扫描二维码关注公众号,回复: 2838352 查看本文章
public int removeElement(int[] nums, int val) {

    int nonMatch = 0; // 指向不匹配元素的下标,开区间

    for (int i = 0 ; i < nums.length ; i ++) {
        if (nums[i] != val) // 要在除了删除元素的位置进行赋值操作
            nums[nonMatch ++] = nums[i];
    }
    return nonMatch;
}

时间复杂度: O ( n ) ,假设数组最多有 n 个元素,那么 i j 最多遍历 2 n 次。
空间复杂度: O ( 1 )

解法二:

每次遇到指定元素时,不是选择跳过,而是将该位置赋上数组最后一个元素的值,下一次仍旧从该位置开始判断,最后将数组最后一个元素丢弃( n 减一);如果没有遇到, i 递增。

 public int removeElement(int[] nums, int val) {

    int n = nums.length;
    for (int i = 0 ; i < n ; ) {
        if (nums[i] == val) { // 只在要删除元素时才进行赋值
            nums[i] = nums[n - 1];
            n --;
        }
        else
            i ++;
    }
    return n;
}

时间复杂度: O ( n ) i n 最多遍历 n 步,赋值操作的数量等于删除的元素数量,比解法一更加有效。
空间复杂度: O ( 1 )

参考:

每日一恋 - LeetCode 26. Remove Duplicates from Sorted Array(删除排序数组中的重复项)
原题链接

猜你喜欢

转载自blog.csdn.net/smartnijun/article/details/81562587