Skip to content

Files

Latest commit

 

History

History
36 lines (26 loc) · 1.28 KB

27. Remove Element.MD

File metadata and controls

36 lines (26 loc) · 1.28 KB

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.

Hint:

Try two pointers.
Did you use the property of "the order of elements can be changed"?.
What happens when the elements to remove are rare?

    public int removeElement(int[] nums, int val) {
        int l = 0, r = nums.length - 1;
        while (l <= r) {
            if (nums[l] == val)
                nums[l] = nums[r--];
            else
                l++;
        }
        return l;
    }

思路 刚开始以为只需要返回值就行,以为太简单,看了输出才知道,同时还要改变nums的值的位置。
题目可以理解为:将不为val的值移到数组的最前面部分。
所以,用2个指针来表示首尾,当前面出现了值为val的情况,则将该位置的值替换成尾指针所指向的值。
同时,首指针也表示了该数组内不含val的个数,返回其值就可以了。