283. Move Zeroes Add to List(把0移动到末尾)
来源:互联网 发布:淘宝卖家有ipad客户端 编辑:程序博客网 时间:2024/05/18 01:38
DescriptionSubmissionsSolutions
Total Accepted: 170660
Total Submissions: 349827
Difficulty: Easy
Contributor: LeetCode
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:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
解法1:不合题意,题中不让用拷贝数组class Solution {public: void moveZeroes(vector<int>& nums) { vector<int> num1;//定义大小的话会用0填充 int sum=0; for(int a:nums) { if(a==0) { sum++;//定义个计数器来几率0的个数 } else {num1.push_back(a);}//不是0的话放前面 } while(sum>0) { num1.push_back(0);//把0插到最后 sum--; } nums.clear();//清空原数组 nums=num1; }};//解法2:class Solution {public: void moveZeroes(vector<int>& nums) { for (int i = 0, j = 0; i < nums.size(); ++i) //一个不停的向后扫(i),找到非零位置,然后和前面那个指针(j)交换位置即可 { if (nums[i]) //如果不是0就交换 { swap(nums[i], nums[j++]); } } }};//解法3:道理同上class Solution {public: void moveZeroes(vector<int>& nums) { int left = 0, right = 0; while (right < nums.size()) { if (nums[right]) { swap(nums[left++], nums[right]); } ++right; } }};
0 0
- 283. Move Zeroes Add to List(把0移动到末尾)
- LeetCode-283. Move Zeroes (JAVA) 移动0到末尾
- Move Zeroes 移动0的个数到数组末尾
- 283. Move Zeroes - 把数组中的0移到末尾
- 把零移动到数组的一端 Move all zeroes to end of array
- Move Zeroes 移动0
- (LeetCode)Move Zeroes -- 将元素0放到末尾
- LeetCode 283. Move Zeroes(移动数字0)
- 283. Move Zeroes (将数组中值为0的元素移到末尾)
- 283. Move Zeroes | 移动零
- 283. Move Zeroes 移动零
- 283. Move Zeroes移动零
- LeetCode283——Move Zeroes(将0移动到数组最后面)
- leetcode283---Move Zeroes(把0移到数组后面)
- Add to List 474. Ones and Zeroes(第十五周)
- LeetCode--Move Zeroes(移动0元素)Python
- Move Zeroes(移动零元素)
- 移动零 Move Zeroes
- nyoj 325 zb的生日(dfs)
- ElasticSearch中默认映射、重索引、索引别名、零停机时间
- 创建线程的方式
- linux下的Find指令
- ArcGIS 10.2栅格计算器实用公式大全
- 283. Move Zeroes Add to List(把0移动到末尾)
- storm任务提交流程
- 【Maven】使用Maven构建多模块项目
- 异步操作的简单笔记
- Cornerstone使用
- 值传递和引用传递
- Agri-Net_POJ1258
- Android自定义View-------为什么重写onMeasure()以及怎么重写
- 函数指针作为参数