Moving Zeros
2015-09-24 06:22
323 查看
Given an array
For example, given
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
Find the first 0, exchange it with the first non-zero number from its right part.
Runtime: 36ms.
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,
numsshould 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.
Find the first 0, exchange it with the first non-zero number from its right part.
Runtime: 36ms.
class Solution { public: void moveZeroes(vector<int>& nums) { int n = nums.size(); if(n <= 1) return; int left = 0, right = 0; while(right < n){ while(nums[left] != 0) left++; //find the first number equals to 0 right = left + 1; while(nums[right] == 0) //find the first number doesn't equal to 0 right++; if(right >= n) return; swap(nums[left], nums[right]); left++; right++; } return; } };
相关文章推荐
- "如何将本地开发的系统迁移到云端,数据存储问题
- H-Index I, II
- "分享:围观龙虎斗:谷歌GCE
- 简洁的for(3)的define
- 云计算学习
- "Nginx服务器在使用HTML5
- "Vcenter
- 分享:高访问量Web应用跨云端迁移的原因:权限和易用性
- 关于hadoop调度问题
- 网络防火墙策略限制定位问题
- Double类parseDouble和valueOf方法的区别
- 提问:从EBS卷中删除Marketplace代码
- "分享:AWS
- **Word Break
- 安装单机Hadoop时格式化HDFS出现问题
- "Hadoop集群运行时总是抛出Child
- Hadoop的Map和Reduce中能不能打开HDFS文件系统中的文件?
- *LeetCode-Single Number III
- Minimum Depth of Binary Tree 解答
- *LeetCode-Single Number II