【LeetCode】27. Remove Element(移除元素)

【LeetCode】27. Remove Element(移除元素)

题目链接:https://leetcode.com/problems/remove-element/description/

难度:Easy

题目描述:

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.

Example:

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

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

 给一个数组,和一个数,要求删除数组中与该数相等的元素并返回新数组的长度。不能用额外的数组,in-palce即不允许移动元素,原位操作。

我的解答虽然AC,但是没有达到要求in-place,而且时间复杂度O(n2)

Java:

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

双指针法

复杂度

时间 O(N) 空间 O(1)

思路

用一个指针记录不含给定数字的数组边界,另一个指针记录当前遍历到的数组位置。只有不等于给定数字的数,才会被拷贝到子数组的边界上。

代码

public class Solution {
    public int removeElement(int[] nums, int val) {
        int pos = 0;
        for(int i = 0; i < nums.length; i++){
            // 只拷贝非给定数字的元素
            if(nums[i] != val){
                nums[pos] = nums[i];
                pos++;
            }
        }
        return pos;
    }
}

交换法

复杂度

时间 O(N) 空间 O(1)

思路

因为题目中并不要求相对顺序保持一致,所以有进一步优化的空间。我们遍历数组时,每遇到一个目标数,就和当前数组结尾交换,并把数组大小减1,如果不是目标数,则检查下一个数字。这样可以减少很多赋值操作。

代码

public class Solution {
    public int removeElement(int[] nums, int val) {
        int size = nums.length, i = 0;
        while(i < size){
            if(nums[i] == val){
                nums[i]=nums[size-1];
                size--;
            } else {
                i++;
            }
        }
        return size;
    }
}



日期:2018/2/23-16:56

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值