LeetCode 27.Remove Element

题目描述

  • Given an array and a value, 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.
  • Examlple :

Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.

问题分析

  • 该题大意便是将给定的元素 val 全部从一个数组中“删除”掉,返回删除后的数组的长度,要求不能用空间复杂度O(1)
  • 其实该题和LeetCode 283.Move Zeroes很像,只不过那题是指定的元素为0,然后将非0元素放在前面,0元素全部放在后面。而这道题,是将 非 val数据放在前面即可,然后统计出非val的所有个数,返回。所以具体方法和 283 题类似,如下:
    • 直接用覆盖的方式,缺点:只得到非val个数,无法将val放在后面(除非再度遍历一次)
    • 交换的方式(当然,也不是严格两数交换)。可以讲非val数据放在前面(并能保证稳定性),且能将 val 数据放在后面
    • 用 p q前后指针实现交换,缺点:不能保证稳定性

经验教训:

  • 这种题型是对一个数组进行原地操作,使得一部分数据(满足某一标准)在前面,另一部分数据(不满足该标准)在后面,并使得前部分数据保持原有顺序(稳定性)。
    双指针做法

代码实现

  • 覆盖的方式:
    public int removeElement(int[] nums, int val) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) {
                nums[k++] = nums[i];
            }
        }
        return k;
    }
  • “交换”的方式(推荐)
    public int removeElement(int[] nums, int val) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) {

                if (i != k) {
                    //swap(nums, i, k++);
                    nums[k++] = nums[i];
                    nums[i] = val;
                }else {
                    k++;
                }

                //nums[k++] = nums[i];
            }
        }
        return k;
    }

    public void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
  • p,q前后指针方法(不能保证稳定性)
    public int removeElement(int[] nums, int val) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int p = 0;
        int q = nums.length - 1;
        while (p <= q) {
            if (nums[p] != val) {
                ++p;
            }else if (nums[q] == val) {
                --q;
            }else {
                swap(nums, p++, q--);
            }
        }
        return p;
    }

     public void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值