好吧,其实这道题刚开始就有大体思路了,但是因为指针命名的混乱,导致逻辑顺序不清晰。初次写的代码对连续0的情况不能很好的处理。
后来吃晚饭的路上又想了想,把想清楚的思路发到手机上,吃完饭回来一下子就做出来了/(ㄒoㄒ)/~~ 因此记录一下。
题目
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.
TAGS
Array Two Pointers
代码
1 1 public class Solution { 2 2 public void moveZeroes(int[] nums) { 3 3 int len =nums.length; 4 4 int pt1=0,pt2=0; 5 5 while(pt2<len){//pt1指向0,pt2逐渐移动 6 6 if(nums[pt1]==0){ 7 7 if(nums[pt2]!=0){ 8 8 nums[pt1]=nums[pt2]; 9 9 nums[pt2]=0; 10 10 pt1++; 11 11 } 12 12 }else{ 13 13 pt1++; 14 14 } 15 15 pt2++; 16 16 } 17 17 } 18 18 }