LeetCode 283. Move Zeroes

283. 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.

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.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.


【题目分析】

给定一个整数数组,把数组中非零元素都移动到数组的左半部分,要求非零元素的相对位置不变。


【思路】

遍历数组,用一个指针记录发现非零元素后的插入位置,然后把数组的后半部分设置为0.

总结:虽然是一道很简单的题目,但是想写出优雅的代码还是有难度的。一定要美美美!


【java代码】

 1 public class Solution {
 2     public void moveZeroes(int[] nums) {
 3         if(nums == null || nums.length <= 1) return;
 4         
 5         int insertPos = 0;
 6         for(int num : nums) {
 7             if(num != 0) nums[insertPos++] = num;
 8         }
 9         
10         while(insertPos < nums.length) {
11             nums[insertPos++] = 0;
12         }
13     }
14 }

 

posted @ 2017-03-02 15:29  Black_Knight  阅读(148)  评论(0编辑  收藏  举报