Leetcode: Move Zeroes

本文探讨了移动开发与前端开发的关键技术与实践方法,包括iOS、Android开发、跨平台框架如React Native与Flutter,以及JavaScript、TypeScript等前端语言的应用。通过实例解析,旨在帮助开发者提升开发效率与质量。
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.

第二遍做法: 双指针压缩法:O(N), 空间:O(1)

实际上就是将所有的非0数向前尽可能的压缩,最后把没压缩的那部分全置0就行了。比如103040,先压缩成134,剩余的3为全置为0。过程中需要一个指针记录压缩到的位置。

 1 public class Solution {
 2     public void moveZeroes(int[] nums) {
 3         if (nums==null || nums.length==0) return;
 4         int cur=0;
 5         for (int i=0; i<nums.length; i++) {
 6             if (nums[i]!=0) {
 7                 nums[cur++] = nums[i];
 8             }
 9         }
10         for (int i=cur; i<nums.length; i++) {
11             nums[i] = 0;
12         }
13     }
14 }

 

Q:如果要把所有的0放在前面而不是后面呢?
A:同样的解题思路,但是是从后向前遍历,将非0数字压缩到后面。

 

 

双指针同向法:O(N^2),不是太好

Two pointer l,r, 

l is to find each 0 in the list, r is to start from l, find first non-0

l, r should not both start from 0, because if r is to the left of l, we don't want to swap it. example: [1, 0]

 1 public class Solution {
 2     public void moveZeroes(int[] nums) {
 3         if (nums==null && nums.length==0) return;
 4         int l=0, r=0;
 5         while (l < nums.length && r < nums.length) {
 6             while (l<nums.length && nums[l]!=0) {
 7                 l++;
 8             }
 9             r = l;
10             while (r<nums.length && nums[r]==0) {
11                 r++;
12             }
13             if (l == nums.length || r == nums.length) break;
14             swap(nums, l, r);
15         }
16     }
17     
18     public void swap(int[] nums, int l, int r) {
19         int temp = nums[l];
20         nums[l] = nums[r];
21         nums[r] = temp;
22     }
23 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值