标签:
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]
.
思路:
统计数组中的0的个数,通过ArrayList的中转,将对应个数的0补在数组后面。
解法:
1 import java.util.ArrayList; 2 3 public class Solution 4 { 5 public void moveZeroes(int[] nums) 6 { 7 int count = 0; 8 ArrayList<Integer> list = new ArrayList<>(); 9 10 for(int i = 0; i < nums.length; i++) 11 { 12 if(nums[i] == 0) 13 count++; 14 else 15 list.add(nums[i]); 16 } 17 18 for(int i = 0; i < count; i++) 19 list.add(0); 20 21 for(int i = 0; i < list.size(); i++) 22 nums[i] = list.get(i); 23 } 24 }
标签:
原文地址:http://www.cnblogs.com/wood-python/p/5732277.html