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

LeetCode: Move Zeroes

这题的关键在于尽量减少运算次数,如果用swap,因为swap的内部机制是3次操作,因此我舍弃了这种方法。

如下的方法的运算次数应该是N+numOfZeros。

 1 public class Solution {
 2     public void moveZeroes(int[] nums) {
 3         int index = 0;
 4         int numOfZeros = 0;
 5         for (int i = 0; i < nums.length; i++)
 6         {
 7             if (nums[i] == 0)
 8             {
 9                 numOfZeros++;
10             }
11             else
12             {
13                 nums[index++] = nums[i];
14             }
15         }
16         for (int i = 0; i < numOfZeros; i++)
17         {
18             nums[nums.length-1-i] = 0;
19         }
20     }
21 }

 

posted @ 2016-04-20 14:30  ying_vincent  阅读(130)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3