0027_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 in place with constant memory.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

Example:
Given input array nums = [3,2,2,3], val = 3

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

JAVA

方法一

与26题相似,也是要返回有效的数组长度并让全部有效数字都在数字的前端。
用两个指针从数组两端向中间扫描即可。P1从左向右扫描,P2从右向左扫描,当P1指向的值不等于val时,result+1并且P1右移,当等于val时,开始移动P2指针,找到第一个不等于val的数与P1交换。
效率依然排在后1/3。。。

public class Solution {
    public int removeElement(int[] nums, int val) {
        int result = 0;
        int p1 = 0;
        int p2 = nums.length - 1;
        int temp;
        while(p1 <= p2){
            while(p1 <= p2){
                if(nums[p1] == val){
                    break;
                }else{
                    ++result;
                    ++p1;
                }
            }
            while(p1 <= p2){
                if(nums[p2] != val){
                    temp = nums[p1];
                    nums[p1] = nums[p2];
                    nums[p2] = temp;
                    ++p1;
                    ++result;
                    --p2;
                    break;
                }else{
                    --p2;
                }
            }
        }
        return result;
    }
}

方法二

看了下效率高的算法,果然简单了很多,虽然时间复杂度同样是 O(N) ,但是代码和思想的复杂程度降了很多,非常简单的思路,效率却很高

    public int removeElement(int[] nums, int val) {
        int news = 0;
        for(int i = 0; i < nums.length; i++){
            if(nums[i] != val){
                nums[news] = nums[i];
                news ++;
            }
        }
        return news;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值