ACM题库~

[LeetCode-Easy]283. Move Zeroes-

2016-08-22  本文已影响241人  AceCream佳

题目:

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;
      }
  }
}
上一篇下一篇

猜你喜欢

热点阅读