Leetcode 283 Move Zeros
阿新 • • 發佈:2018-12-16
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.
Example:
Input:[0,1,0,3,12]
Output:[1,3,12,0,0]
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
方法1:遍歷陣列,找到0元素,然後尋找該0元素後面第一個非0元素,並與其交換位置(複雜度太高!)
class Solution { public void moveZeroes(int[] nums) { // Arrays.sort(nums); for(int i=0;i<nums.length;i++) { //尋找0 if(nums[i]==0) { //尋找該元素後面第一個非0元素,並與其交換 for(int j=i+1;j<nums.length;j++) { if(nums[j]!=0){ nums[i]=nums[j]; nums[j]=0; break; } } } } // System.out.println(Arrays.toString(nums)); } }
方法2: 遍歷陣列,若當前的數不為0,依次放入nums,放完後,判斷指標是否到達陣列長度位置,沒有的話就在後面插入0
class Solution { public void moveZeroes(int[] nums) { //方法2 遍歷陣列,若當前的數不為0,依次放入nums //放完後,判斷指標是否到達陣列長度位置,沒有的話就在後面插入0 int point=0; for(int i=0;i<nums.length;i++) { if(nums[i]!=0){ nums[point++]=nums[i]; // point++; } } while(point<nums.length){ nums[point++]=0; } } }