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

来源:互联网 发布:悠唐网络是真的吗 编辑:程序博客网 时间:2024/05/20 19:16

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;    }}
0 0
原创粉丝点击