LeetCode oj 283. Move Zeroes (選擇排序)

283. Move Zeroes

 
 My Submissions
  • Total Accepted: 122129
  • Total Submissions: 262841
  • Difficulty: Easy

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'都移到最後面,並且不能copy數組和必須最少的操作數
想一想選擇排序就有思路了,選取第一個不是0的元素,把他放到第一位,再選取第二個不是0的元素,放到第二位,循環一遍就可以了
public class Solution {
    public void moveZeroes(int[] nums) {
        int len = nums.length;
        int index = 0;
        for(int i=0;i<len;i++){
            if(nums[i] != 0){
                int temp = nums[index];
                nums[index] = nums[i];
                nums[i] = temp;
                index++;
            }
        }
    }
}


發佈了244 篇原創文章 · 獲贊 18 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章