[LeetCode-Easy]283. Move Zeroes-把数组中所有0移动到最后

题目:

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;
      }
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容