[leetcode]解决Move Zeroes的一点小心得
2017-11-19 21:08
295 查看
本次选择的题目是
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.
Solution:
利用双指针的方法,一个指针忽视0,一个指针不断往前,忽视0的指针利用不断往前的指针将0替换到按顺序的非0数。
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.
Solution:
利用双指针的方法,一个指针忽视0,一个指针不断往前,忽视0的指针利用不断往前的指针将0替换到按顺序的非0数。
class Solution { public: void moveZeroes(vector<int>& nums) { int j = 0; // move all the nonzero elements advance for (int i = 0; i < nums.size(); i++) { if (nums[i] != 0) { nums[j++] = nums[i]; } } for (;j < nums.size(); j++) { nums[j] = 0; } } };
相关文章推荐
- [leetcode]解决Climbing Stairs的一点小心得
- [leetcode]解决Kth Largest Element in an Array的一点小心得
- [leetcode]解决Clone Graph的一点小心得
- [leetcode]解决House Robber的一点小心得
- [leetcode]解决Majority Element的一点小心得
- [leetcode]解决Symmetric Tree的一点小心得
- [leetcode]解决Search a 2D Matrix II的一点小心得
- [leetcode]解决Minimum Height Trees的一点小心得
- [leetcode]解决Assign Cookies的一点小心得
- [leetcode]解决Same Tree的一点小心得
- [leetcode]解决Burst Balloons的一点小心得
- [leetcode]解决Maximum Subarray的一点小心得
- 系统很慢一点解决心得
- 解决堆损坏的一点心得
- 关于信号槽连接地方的一点心得,一个问题困扰了一下午才解决,纪念一下。
- CGAL配置的一点心得(各种错误的解决办法)
- 解决Dynamips使用时CPU占用率100%的一点个人心得
- LeetCode编程练习 - Move Zeroes学习心得
- 客户端用https连接服务器web service的一点心得
- leetcode_303. Range Sum Query - Immutable ? 待解决