自己的解法,用了两个pointer。速度比较慢。
答案很简单,用了一个pointer记录非零数insert的position, 并且用iteration做循环。
My code, 1st:
public class Solution {
public void moveZeroes(int[] nums) {
/** two pointers:
* 1st first zero, 2nd curr scan iterm
*/
int zero = -1, curr = 0;
for (int i=0; i<nums.length; i++) {
if (nums[i] != 0) continue;
else {
zero = i;
break;
}
}
if(zero == -1) return;
for (int i=zero+1; i<nums.length; i++) {
if (nums[i]==0) continue;
else {
swap(nums, zero, i);
zero ++;
}
}
}
private void swap(int[] nums, int a, int b) {
int tmp = nums[a];
nums[a] = nums[b];
nums[b] = tmp;
}
}
看了答案之后:
这种做法问题是改变了array本身。
public class Solution {
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) return;
int curr = 0;
for (int num : nums)
if (num != 0) nums[curr++] = num;
while (curr < nums.length)
nums[curr++] = 0;
}
}
想法:在scan的时候没有遇见0,就只向后移动。
does not matter, just 1ms.
时间: O(n);
空间:O(n);
Never stop. Oct 19 2016
网友评论