Problem 27

Remove Element

Posted by Ruizhi Ma on December 23, 2019

问题描述

https://leetcode.com/problems/remove-element/

解决思路(2019-12-23)

  1. use two pointer, the first pointer marks the element which is different from the val, the second pointer traverses the whole array
  2. if the element is the same as the val, move the second pointer only
  3. If the element is different from the val, move the first pointer, and copy the value of second pointer to the first, move the second pointer

问题解惑

  1. use two pointer, the first pointer marks the element which is different from the val, the second pointer traverses the whole array
  2. if the element is the same as the val, move the second pointer only
  3. If the element is different from the val, move the first pointer, and copy the value of second pointer to the first, move the second pointer

代码

class Solution {
    public int removeElement(int[] nums, int val) {
        
        //corner case
        if(nums == null || nums.length == 0) return 0;
        
        int first = 0;
        int second = 0;
        
        while(second < nums.length){
            if(val == nums[second]){
                second++;
                continue;
            }
            
            if(nums[second] != val){
                nums[first] = nums[second];
                first++;
                second++;
            }
        }
        
        return first;
    }
}

解决思路(2019-05-06)

思路没什么可说的,但要注意 nums[res++] = nums[i] 这个,应该先执行数组赋值,再执行res++操作。

问题解惑

我一开始很疑惑,为什么需要我返回的明明是res,但Leetcode给我的output却包含了remove之后的数组呢?并且,我尝试了一下,将 nums[res++] = nums[i]改成res++,看能不能通过测试,结果是不可以!!!当然,“不可以”我是理解的,因为题目说了length = 2, with the first巴拉巴拉。可为什么我明明只返回了res,但系统却能读取到我remove之后的数组呢(output给出的是我remove之后的数组)?
原来玄机如下,题目也给出了说明:
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.

代码

package leetcode;

public class RemoveElement {
    public static int removeElement(int[] nums, int val){
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int res = 0;
        for (int i = 0; i < nums.length; i++){
            if (nums[i] != val){
                nums[res++] = nums[i];
            }
        }
        return res;
    }
}