0
点赞
收藏
分享

微信扫一扫

【LeeCode】27. 移除元素

雪域迷影 2023-01-15 阅读 67

【题目描述】

给你一个数组 ​​nums​ 和一个值 ​​val​​,你需要 ​​原地​​ 移除所有数值等于 ​​val​ 的元素,并返回移除后数组的新长度。

不要使用额外的数组空间,你必须仅使用 ​​O(1)​​ 额外空间并 ​​原地 ​​修改输入数组

元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。

​​​​https://leetcode.cn/problems/remove-element/​​

【LeeCode】27. 移除元素_System

【示例】

【LeeCode】27. 移除元素_数组_02

【代码】admin

import java.util.*;
// 2023-1-15

class Solution {
public int removeElement(int[] nums, int val) {
int index = 0;
for (int num: nums){
if (num != val){
nums[index] = num;
index++;
}
}
// System.out.println(Arrays.toString(nums));
return index;
}
}

public class Main {
public static void main(String[] args) {
new Solution().removeElement(new int[]{3,2,2,3}, 3); // 输出: 2, nums = [2,2]
new Solution().removeElement(new int[]{0,1,2,2,3,0,4,2}, 2); // 输出: 5, nums = [0,1,4,0,3]
}
}

举报

相关推荐

0 条评论