[LeetCode-283] Move Zeroes
2015-12-24 00:32
375 查看
写在前面:待补充。。。
我的解答:
不用vector,用普通数组,以下是完整代码
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. For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. Note: <font color=red> 1.You must do this in-place without making a copy of the array. 2.Minimize the total number of operations. </font>
我的解答:
class Solution { public: void moveZeroes(vector<int>& nums) { int nums_length = nums.size(); int i = nums_length - 2; int j = 0; for(i; i >= 0; i--){ if (nums[i] == 0) { for(j = i; j < (nums_length-1); j++){ nums[j] = nums[j+1]; } nums[nums_length - 1] = 0; } } } };
不用vector,用普通数组,以下是完整代码
#include <iostream> using namespace std; int main(int argc, const char * argv[]) { int nums[9] = {1,0,7,9,0,6,78,0,99}; int nums_length = sizeof(nums) / sizeof(nums[0]); int i = nums_length - 2; int j = 0; int k = 0; for(i; i >= 0; i--){ if (nums[i] == 0) { for(j = i; j < (nums_length-1); j++){ nums[j] = nums[j+1]; } nums[nums_length - 1] = 0; } } for (k = 0; k < nums_length; k++) { cout << nums[k] << " "; } return 0; }
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C++联合体转换成C#结构的实现方法
- C#实现的算24点游戏算法实例分析
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题