27. Remove Element

来源:互联网 发布:手机数据永久删除 编辑:程序博客网 时间:2024/06/10 08:36

27. 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.

翻译

给定一个数组和一个值,删除该值的所有实例,并返回新的长度。

不要为另一个数组分配额外的空间,您必须使用常量内存来进行此操作。

元素的顺序可以改变。没有什么你离开超过新的长度。

示例:
给定输入数组nums = [3,2,2,3],val =3

你的函数应该返回length = 2,num的前两个元素是2。

解题思路

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

欢迎加入中科院开源软件自习室:631696396

欢迎加入中科院开源软件自习室

原创粉丝点击