LeetCode-Java-27. Remove Element

53 篇文章 0 订阅
53 篇文章 0 订阅

题目

Given an array nums and a value val, remove all instances of that value in-place and return the new length.
给定一个数组num和一个值,在这个数组中删除这个值得全部实例并且返回新的长度
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
不要为其他的数组分配额外的空间,你必须修改输入的数组,用O(1)的空间
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
元素的顺序可以改变,你的新长度并不重要。


Example 1:
例子1
Given nums = [3,2,2,3], val = 3,
给你一个数组和val
Your function should return length = 2, with the first two elements of nums being 2.
你的函数应该能够返回length=2,同时nums中前两个元素为2。
It doesn't matter what you leave beyond the returned length.
你返回长度之后是什么并不重要。
Example 2:
例子2
Given nums = [0,1,2,2,3,0,4,2], val = 2,
给你一个数组nums和val
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
你的函数能够返回length=5,同时nums中前5个元素应该包含0,1,3,0,4。
Note that the order of those five elements can be arbitrary.
记住这个这5个元素的顺序任意
It doesn't matter what values are set beyond the returned length.
你返回长度之后是什么并不重要
Clarification:
澄清
Confused why the returned value is an integer but your answer is an array?
混淆:为什么要求返回一个值,你却返回一个数组?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
注意输入的数组是通过引用传入,这意味着修改输入的数组将会被调用者知道
Internally you can think of this:
在内部你可以这样想

// nums is passed in by reference. (i.e., without making a copy)
num通过引用传入
int len = removeElement(nums, val);
// any modification to nums in your function would be known by the caller.
调用者知道你的函数对nums的修改
// using the length returned by your function, it prints the first len elements.
使用你的函数返回的length,可以打印出前几个元素
for (int i = 0; i < len; i++) {
    print(nums[i]);
}

代码

class Solution {
    public int removeElement(int[] nums, int val) {
        int len = nums.length;
        int reLen = 0 ;
        for(int i = 0 ;i<len;i++)
        {
            int num = nums[i];
            if(num!=val)
            {
                nums[reLen++] = num;
            }
        }
        return reLen;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值