星空网 > 软件开发 > Java

【leetcode】Move Zeroes

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:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

一开始的想法是,遍历数组,遇到0就往后移,一直移动最后一步。代码如下

public class Solution {  public static void moveZeroes(int[] nums) {    for (int i = 0; i < nums.length; i++) {      if (nums[i] == 0 && i != (nums.length - 1)) {        for (int j = i; j < nums.length - 1; j++) {          int temp = nums[j];          nums[j] = nums[j + 1];          nums[j + 1] = temp;        }      }    }  }}

但是,发现001这个测试用例不对。

恩,发现问题了,因为第一个数为0,第二个0就没办法移动到最后了。

换一种思路,不遍历找0,而是遍历找非0,遇到非0,且不在第一位,就往前移,直到它前面不是0为止。

public class Solution {  public static void moveZeroes(int[] nums) {    for (int i = 0; i < nums.length; i++) {      if (nums[i] != 0 && i != 0) {        for (int j = i; j > 0 && nums[j - 1] == 0; j--) {          int temp = nums[j - 1];          nums[j - 1] = nums[j];          nums[j] = temp;        }      }    }  }}

这样就解决了

其他方法

public static void moveZeroes(int[] nums) {    int i = 0, j = 0;    for (i = 0; i < nums.length; i++) {      if (nums[i] != 0) {        if (j != i) {          nums[j] = nums[i];          nums[j] = 0;        }        j++;      }    }  }

这种方法i遍历数组,只有当i指向为非0时,且ji不同时,j后移,将j处的数改成i处的数,并使i处的数字为0,ij同步后移,而当i指向为0时,只有i后移,j仍然指向0处。

还有一种更简单的方法

public void moveZeroes(int[] nums) {  if (nums == null || nums.length == 0) return;      int insertPos = 0;  for (int num: nums) {    if (num != 0) nums[insertPos++] = num;  }      while (insertPos < nums.length) {    nums[insertPos++] = 0;  }}




原标题:【leetcode】Move Zeroes

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

如何利用FBN库存页面管理我们的库存?:https://www.kjdsnews.com/a/1701434.html
亚马逊高级A+页面更新!转化率可提升1倍!:https://www.kjdsnews.com/a/1701435.html
出海家居品牌「乐歌」拟募资5亿扩建美国海外仓:https://www.kjdsnews.com/a/1701436.html
如何优化你的阿里巴巴产品标题?:https://www.kjdsnews.com/a/1701437.html
交付10亿个包裹,亚马逊当日达配送网络再提速:https://www.kjdsnews.com/a/1701438.html
DTC消费电子品牌Homified完成种子轮融资:https://www.kjdsnews.com/a/1702403.html
TikTok 将推出先买后付服务 :https://www.goluckyvip.com/news/188219.html
深圳有没有比较好玩的景点 深圳有没有比较好玩的景点推荐一下:https://www.vstour.cn/a/366175.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流