每周一算法2017.12.1
Move Zeroes
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.
Note:
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.
描述:给定一个数字数组,写一个方法将所有的“0”移动到数组尾部,同时保持其余非零元素的相对位置不变。 例如,给定nums = [0, 1, 0, 3, 12],在调用你的函数之后,nums应该变为[1, 3, 12, 0, 0]。
备注:完成这项操作,不得复制该数组。最小化总共的操作数。
分析:这道题让我们将一个给定数组中所有的0都移到后面,把非零数前移,要求不能改变非零数的相对应的位置关系,而且不能拷贝额外的数组,那么只能用替换法in-place来做,需要用两个指针,一个不停的向后扫,找到非零位置,然后和前面那个指针交换位置即可。
时间复杂度&空间复杂度
时间 O(N) 空间 O(1)
Java
class Solution {
public void moveZeros(int[] nums) {
int j = 0;
int temp = 0;
for (int i=0; i<nums.length; i++){
if (nums[i]!=0){
temp = nums[i];
nums[i]=nums[j];
nums[j]=temp;
j++;
}
}
}
}
C
void moveZeroes(int* nums, int numsSize) {
int i,j=0;
for(i=0;i<numsSize;i++){
if(nums[i]!=0){
nums[j++]=nums[i];
}
}
while(j<numsSize){
nums[j++]=0;
}
}
C++
class Solution {
public:
void moveZeroes(vector<int>& nums) {
size_t pos = 0;
for(size_t i = 0;i != nums.size();++i){
if(nums[i] != 0) nums[pos++] = nums[i];
}
for(;pos != nums.size();++pos)
nums[pos] = 0;
}
};
Python
class Solution(object):
def moveZeroes(self, nums):
idx =0
for i in xrange(len(nums)):
if nums[i]:
nums[i], nums[idx] = nums[idx], nums[i]
idx+=1
Swift
class Solution {
func moveZeroes(_ nums: inout [Int]) {
var slow = 0, fast = 0
while fast < nums.count {
if nums[fast] != 0 {
if nums[slow] == 0 {
(nums[slow], nums[fast]) = (nums[fast], nums[slow])
}
slow += 1
}
fast += 1
}
}
}
本题来自leetcode 283.Move Zeroes