leetcode--Move Zeroes
2016-12-26 20:51
302 查看
题目:Move Zeroes
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.
题目解析:把数组的0后移到最后,数字顺序保持不变。
One:把不为0的数目记录,同时把不为的数全部前移。最后把后几位置为0.
Two:
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,
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.
题目解析:把数组的0后移到最后,数字顺序保持不变。
One:把不为0的数目记录,同时把不为的数全部前移。最后把后几位置为0.
public class Solution { public void moveZeroes(int[] nums) { if(nums==null||nums.length==0)return; int counter = 0; int len = nums.length; for(int i = 0;i<len;i++){ nums[i-counter] = nums[i]; if(nums[i]==0) counter++; } for(int i =len-counter;i<len;i++){ nums[i] = 0; } } }
Two:
public void moveZeroes(int[] nums) { int j = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] != 0) { int temp = nums[j]; nums[j] = nums[i]; nums[i] = temp; j++; } } }
相关文章推荐
- (LeetCode)Move Zeroes -- 将元素0放到末尾
- leetcode 283:Move Zeroes
- LeetCode-283 Move Zeroes
- Leetcode学习(34)—— Move Zeroes
- leetcode 283--Move Zeroes
- leetcode 283 Move Zeroes
- Leetcode-Move Zeroes
- leetcode Move Zeroes
- [LeetCode]283. Move Zeroes(把0移到数组后面)
- LeetCode 283:Move Zeroes
- [LeetCode]Move Zeroes
- LeetCode || Move Zeroes
- LeetCode: Move Zeroes
- 【leetcode】Move Zeroes
- LeetCode Move Zeroes 最小堆
- [LeetCode] Move Zeroes
- LeetCode - Move Zeroes
- Leetcode之Move Zeroes 问题
- LeetCode(283) Move Zeroes
- LeetCode题解:Move Zeroes