LeetCode 283 Move Zeroes题解
2016-12-05 21:48
302 查看
题目地址:https://leetcode.com/problems/move-zeroes/
to the end of it while maintaining the relative order of the non-zero elements.
给定一个数组,将元素‘0’都移动到非‘0’元素后面。
For example, given
be
例如,给定nums=【0,1,0,3,12】,经过处理,nums=【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.
题目:
Given an arraynums, write a function to move all
0's
to the end of it while maintaining the relative order of the non-zero elements.
给定一个数组,将元素‘0’都移动到非‘0’元素后面。
For example, given
nums = [0, 1, 0, 3, 12], after calling your function,
numsshould
be
[1, 3, 12, 0, 0].
例如,给定nums=【0,1,0,3,12】,经过处理,nums=【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.
算法设计:
用两个int型数值i,j分别记录0元素位置和非0元素位置,j用于向后遍历元素,如果遍历到非0元素,如果i,j不指向同一位置,就j指向的元素复制到i的位置,将j位置置0,如果指向同一位置,将i也向后挪动一个位置一遍于j同步。Java代码实现:
public class Solution { public void moveZeroes(int[] nums) { int i=0; int j=0; while(j<nums.length) { if(nums[j]!=0) { if(j!=i) { nums[i++] = nums[j]; nums[j] = 0; } else { ++i; } } ++j; } } }
相关文章推荐
- (数组)leetcode 283:Move Zeroes
- 【LEETCODE】283-Move Zeroes
- LeetCode283——Move Zeroes(将0移动到数组最后面)
- LeetCode 283 Move Zeroes
- Leetcode 283 Move Zeroes
- LeetCode(283) Move Zeroes
- LeetCode题解:Move Zeroes
- [Leetcode 283]Move Zeroes
- leetcode_c++:Move Zeroes(283)
- LeetCode 283:Move Zeroes
- 【LeetCode】283 Move Zeroes
- LeetCode 283 Move Zeroes(移动全部的零元素)
- leetcode——283——Move Zeroes
- LeetCode number 283 move zeroes的一种易于理解的解法
- Leetcode 283 Move Zeroes
- <LeetCode OJ> Move Zeroes【283】
- [LeetCode283]Move Zeroes
- leetcode-283-Move Zeroes
- leetcode 283:Move Zeroes
- Move Zeroes | leetcode 283 【Java解题报告】