leetcode | Remove Element

来源:互联网 发布:装修画图傻瓜软件 编辑:程序博客网 时间:2024/05/23 21:23

Given an array and a value, remove all instances of that value in place and return the new length.

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

题意:从数组中去除某个值,返回新数组的长度;注意在去除完毕后数组中的元素应该变化了,即出现value的位置都被替换掉了,最后一句的意思一开始我理解错了,以为是只要返回长度就行了,所以提示错误,仔细读了意思是新长度后面的元素值任意,也就是说,新数组的总长度可以保持不变,但是新长度之前的元素要正确,后面的无所谓。

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








0 0