[leetcode]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:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.2.

It doesn't matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

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.

解法一

思路

果然刷题是有用的啊!!!!这道题和[leetcode]21.Merge Two Sorted Lists 的思路完全没有区别,同样是用快慢指针,快指针用来遍历数组,慢指针用来修改数组的值,如果快指针所指的值与要删除的值相同,则快指针往前走(意味着这个值我们不想保存),如果快指针所指的值与要删除的值不同,我们就把当前值保存到慢指针的位置,然后快慢指针都往前走。

代码

class Solution {
    public int removeElement(int[] nums, int val) {
        int j = 0; //慢指针
        int len = nums.length;
        for(int i = 0; i < len; i++) { //快指针
            if(nums[i] != val) {
                nums[j++] = nums[i];
            }
        }
        return j;
    }
}

解法二

思路

在discuss区还看了另外一种解法,其实也是用两个指针,i指针从前往后走,len指针从后往前走,把所有非val值都能移到指针相遇位置的前面,所以最后返回len即可,一种很奇妙的方法。在这个方法中,还学到了for循环的i<value中,这个value是可变的,是可动态调整的。

代码

class Solution {
    public int removeElement(int[] nums, int val) {
        int len = nums.length;
        for(int i = 0; i < len; i++) {
            while(nums[i] == val && i < len) {
                nums[i] = nums[--len];
            }
        }
        return len;
    }
}

猜你喜欢

转载自www.cnblogs.com/shinjia/p/9722547.html