算法題丨Move Zeroes

描述

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:
1.You must do this in-place without making a copy of the array.
2.Minimize the total number of operations.git

示例

Given nums = [0, 1, 0, 3, 12], after calling your function, 
nums should be [1, 3, 12, 0, 0].

算法分析

難度:低
分析:給定一個數組,將全部爲0的元素都移動到數組的末尾,並保持非0的元素排序保持不變。
思路:首先,思考知足第1個條件很簡單,就是遍歷數組,判斷當前元素是否爲0,若是是0,將0跟當前元素互換一下,遍歷完數組就能夠了。可是這樣處理的話,並不能保證非0元素排序不變,因此,咱們放棄這種思路。
那怎麼保持非0元素的排序呢?咱們考慮記錄當前非0的個數索引index,遍歷的時候,若是是非0元素,將數組[index]記錄該元素,非0的個數索引index加1,下一個非0的就會記錄在數組[index+1]中,依次類推,這樣其實實現了非0元素順序保存。最終數組[0,index)即爲保持排序的非0元素。剩下的就很簡單了,將數組[index]以後的元素所有置0就能夠了。github

代碼示例(C#)

public void MoveZeroes(int[] nums)
{
    int index = 0;
    for (int i = 0; i < nums.Length; ++i)
    {
        if (nums[i] != 0)
        {
            //非0元素,記錄排序
            nums[index++] = nums[i];
        }
    }
    //非0元素以後的元素全置0
    for (int i = index; i < nums.Length; ++i)
    {
        nums[i] = 0;
    }
}

複雜度

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

附錄

相關文章
相關標籤/搜索