您好,欢迎来到暴趣科技网。
搜索
您的当前位置:首页Leetcode #27. Remove Element 移除元素 解题报告

Leetcode #27. Remove Element 移除元素 解题报告

来源:暴趣科技网

1 解题思想

原题不就是说,给定数组,和一个目标值。。把数组里等于目标值的给删了么,最后还剩几个。。

这道题虽然只说有几个。。但是似乎还是要交换的,不只是单纯的统计。。检查的时候会遍历检查的

2 原题


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.

3 AC解

public class Solution {
    /**
     * 这世道水题,做法很简单,一个当前位置i一个当前长度n,顺着找,如果相等就把当前有效位置的最后一个放倒i上就好,然后n--,自然就没了
     * 如果不是的话,i++,继续找下一个,就这样
     */
    public int removeElement(int[] nums, int val) {
        int n=nums.length;
        int i=0;
        while(i<n){
            if(nums[i]==val){
                n--;
                nums[i]=nums[n];
            } else{
                i++;
            }
        }
        return n;
    }
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- baoquwan.com 版权所有 湘ICP备2024080961号-7

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务