【數論】C040_「移除零」「移除元素」(雙指針 n-k)

C_01 移除零

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

Note:

  • You must do this in-place without making a copy of the array.
  • Minimize the total number of operations.
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

方法一:雙指針

算法

基於數組 nums 中非零元素有 k 個,值爲 0 元素必然有 n-k 個的事實,我們可以這樣設計算法。

  • 遇到非 0 我們只需常規覆蓋當前元素,然後指針 k++。
  • 最後把 n-k 個元素賦值爲 0 即可。
public void moveZeroes(int[] nums) {
    int N = nums.length;
    int k = 0;
    for (int n : nums) {
        if (n != 0)
            nums[k++] = n;
    }
    for (int i = k; i < N; i++)
        nums[i] = 0;
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(1)O(1)

C_02 移除元素

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.

方法一:雙指針

基於數組 nums 中值爲 val 元素有 k 個,值爲非 val 元素必然有 n-k 個的事實,我們可以這樣設計算法。

  • 遇到非 val 我們只需常規覆蓋當前元素,然後指針 k++。
  • 最後返回 k 這幾個非 val 元素即可。
public int removeElement(int[] nums, int val) {
    int k = 0, N = nums.length;

    for (int n : nums) {
        if (n != val) 
            nums[k++] = n;
    }
    return k;
}

複雜度分析

  • 時間複雜度:O(n)O(n)
  • 空間複雜度:O(1)O(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章