• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

xxxqqq

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

Move Zeroes

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.

Notice
  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.
Example

Given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [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         if(nums==null|nums.length==0) return;
 9         int pos = 0;
10         for(int i=0;i<nums.length;i++){
11             if(nums[i]!=0){
12                 swap(nums, i, pos++);
13             }
14         }
15     }
16     private void swap(int[] nums, int i, int j){
17         int temp = nums[i];
18         nums[i]=nums[j];
19         nums[j]=temp;
20     }
21 }

 

posted on 2017-05-10 15:22  xxxqqq  阅读(306)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3