移动零

描述:

      给一个数组nums写一个函数将0移动到数组的最后面,非零元素保持原数组的顺序.

注意事项:

     1.必须在原数组上操作;
     2.最小化操作数。

样例:

     给出nums=[0, 1, 0, 3, 12], 调用函数之后,nums=[1, 3, 12, 0, 0].

代码如下:

 1 public class Solution {
 2     /**
 3      * @param nums an integer array
 4      * @return nothing, do this in-place
 5      */
 6     public void moveZeroes(int[] nums) {
 7         // Write your code here
 8         
 9         int n=nums.length;
10         int total_Nzero=0;//数组中不为0的元素的总数
11         int x=0;
12         for(int i=0;i<n;i++){
13             if(nums[i]!=x){
14               nums[total_Nzero]=nums[i];
15               total_Nzero++;}
16         }
17         
18         for(int i=total_Nzero;i<n;i++){
19               nums[i]=x;
20         }
21     }
22 }

法二:

 1 public class Solution {
 2     /**
 3      * @param nums an integer array
 4      * @return nothing, do this in-place
 5      */
 6     public void moveZeroes(int[] nums) {
 7         int n = nums.length;
 8         int small = -1;
 9         int large = 0;
10         int x = 0;
11         while(large < n){
12             if(nums[large]!=x){
13                 small++;
14                 swap(nums,small,large);
15             }
16             large++;
17         }
18     }
19     public void swap(int[] A,int i,int j){
20         int tmp = A[i];
21         A[i] = A[j];
22         A[j] = tmp;
23     }
24 
25     }

 

 

 

转载于:https://www.cnblogs.com/suya1119/p/6526509.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值