leetcode 283. Move Zeroes
2016-04-02 10:49
477 查看
Given an array
to the end of it while maintaining the relative order of the non-zero elements.
For example, given
be
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
void moveZeroes(int*nums, int numsSize) {
if (numsSize < 2)
return;
int k = 0;
while (k < numsSize - 1)
{
while (k < numsSize - 1 && nums[k] != 0)
k++;
if (k == numsSize - 1)
return;
int k1 = k;
while (k1 < numsSize && nums[k1] == 0)
k1++;
if (k1 == numsSize)
return;
int k2 = k1;
while (k2 < numsSize && nums[k2] != 0)
k2++;
for (int i = 0; i < k2 - k1; i++)
{
nums[k + i] = nums[k1 + i];
nums[k1 + i] = 0;
}
k += k2 - k1;
}
}
accepted
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.
void moveZeroes(int*nums, int numsSize) {
if (numsSize < 2)
return;
int k = 0;
while (k < numsSize - 1)
{
while (k < numsSize - 1 && nums[k] != 0)
k++;
if (k == numsSize - 1)
return;
int k1 = k;
while (k1 < numsSize && nums[k1] == 0)
k1++;
if (k1 == numsSize)
return;
int k2 = k1;
while (k2 < numsSize && nums[k2] != 0)
k2++;
for (int i = 0; i < k2 - k1; i++)
{
nums[k + i] = nums[k1 + i];
nums[k1 + i] = 0;
}
k += k2 - k1;
}
}
accepted
相关文章推荐
- HDU 1875 畅通工程再续 最小生成树
- 【JQuery】使用wrap()和wrapInner()方法包裹元素和内容
- HDU 1875 畅通工程再续 最小生成树
- C语言18个经典问题答录
- fragment的使用
- 前端代码的一些基本规范使用
- Android 消息循环机制源码分析
- Nagle算法
- [Android实例] 推荐给你们一个好用的ListView、RecyclerView适配器
- Android 6.0 wif的变动
- 【笔试/面试】数组及其内存结构
- linux中的热插拔和mdev机制
- Html5 手机wap开发、微信开发、APP开发的优缺点-创业者必知
- Android Context的一些总结
- Android Studio安装插件
- 实现power(base,exponent),不用库函数和for循环
- 自定义view之圆形ImageView
- 在windows和Python2.7下,安装Scapy
- Android中Cursor类的概念和用法
- git入门