LeetCode 27 Remove Elements

思路

同向双指针。如果没遇到给定的val,就让nums[index]=nums[i],其中index为指示当前可覆盖位置的指针(慢指针),i为遍历整个数组所用的指针(快指针)。如果遇到了,就只移动i指针,直到遇到的不是val。

复杂度

时间复杂度O(n), 空间复杂度O(1)

代码

class Solution {
    public int removeElement(int[] nums, int val) {
        if(nums.length == 0)
            return 0;
        int index = 0;
        for(int i = 0; i < nums.length; i++) {
            if(nums[i] != val) {
                nums[index] = nums[i];
                index++;
            }
        }
        return index;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36754149/article/details/88572868
今日推荐