Leetcode--Java--27. Remove Element

本文介绍了一种在原地移除数组中特定值并返回新长度的算法。通过双指针技巧实现,快指针搜索非目标值,慢指针记录有效元素。适用于数值处理与数组操作场景。

题目描述

Given an array nums and a value val, 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 by modifying the input array in-place with O(1) extra memory.

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

样例描述

Example 1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2]
Explanation: Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted.
Example 2:

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3]
Explanation: Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length.
 

Constraints:

0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100

思路

  1. 双指针思路,使用一个慢指针和一个快指针,快指针j用来寻找不等于val的值,慢指针i负责索引位置,等待接收j指向的值,i同时也表示数组中不等于val的个数
  2. 本题思路与下面这题极其相似,可以参考一下
    Leetcode–Java–26. Remove Duplicates from Sorted Array

代码

class Solution {
    public int removeElement(int[] nums, int val) {
          int i = 0; //即作为索引,也表示不等于val的值的个数
          for (int j = 0; j < nums.length; j++){
              //j指向的值等于val就不断往后走,直到指向的不等于val,然后调整归位
              if (nums[j] != val){
                  nums[i] = nums[j];
                  i ++; 
              }
          }
          return i;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值