leetcode[Move Zeroes]

xiaoxiao2021-02-27  214

解法一:

public class Solution { public void moveZeroes(int[] nums) { for(int i = 0; i < nums.length; i++){ for(int j = 0; j < nums.length - i - 1; j++){ if(nums[j] == 0){ int temp = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = temp; } } } } } 解法二(参考了[Remove Duplicates from Sorted Array]):

public class Solution {   public void moveZeroes(int[] nums) { int pos = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] != 0){ nums[pos++] = nums[i]; } } for(int i = pos; i < nums.length; i++){ nums[i] = 0; } } }

转载请注明原文地址: https://www.6miu.com/read-12467.html

最新回复(0)