《LeetCode力扣练习》第283题 移动零 Java
一、资源
-
题目:
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
请注意 ,必须在不复制数组的情况下原地对数组进行操作。
示例 1:
输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]示例 2:
输入: nums = [0]
输出: [0]提示:
1 <= nums.length <= 104 -231 <= nums[i] <= 231 - 1进阶:你能尽量减少完成的操作次数吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/move-zeroes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 -
上代码(经过线上OJ测试)
/** * Created with IntelliJ IDEA. * * @author : DuZhenYang * @version : 2022.03.01 18:01:48 * description : */ public class LeetCode { public void moveZeroes(int[] nums) { int n = nums.length; int left = 0; int right = 0; while (right < n) { if (nums[right] != 0) { swap(nums, left, right); left++; } right++; } } private void swap(int[] nums, int left, int right) { int temp = nums[left]; nums[left] = nums[right]; nums[right] = temp; } }
1369

被折叠的 条评论
为什么被折叠?



