[LeetCode-Easy]283. Move Zeroes-把數組中所有0移動到最后

題目:

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.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
1.You must do this in-place without making a copy of the array.
2.Minimize the total number of operations.

思路:

此題是讓我們把數組中所有的0元素,移動到數組的結尾,要求我們不復制這個數組做改變,并且盡量減少操作次數。思考了一下,想到一個可以節省代碼量并且讓時間復雜度保持在O(n)的方案。

想法是這樣的:既然規定不復制這個數組,那就在它本身做文章了,我遍歷這個數組,如果出現不是零的數,就讓它把原數組的第一位替換掉,這樣的話,這個數組就是去掉所有0的狀態了,在這之后,我們把這個數組結尾補0,一直補到原長度就好了。很簡單!

代碼:

public class Solution {
  public void moveZeroes(int[] nums) {
      int newArrayIndex = 0;
      for (int i = 0; i < nums.length; i++) {
          if (nums[i] != 0) {
            nums[newArrayIndex++] = nums[i];
          }
      }
    for (int i = newArrayIndex; i < nums.length; i++) {
            nums[i] =  0;
      }
  }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容