题目:
给定一个数组nums,写一个函数,将数组中所有的0挪到数组的末尾,⽽维持其他所有非0元素的相对位置。
举例: nums = [0, 1, 0, 3, 12],函数运⾏后结果为[1, 3, 12, 0, 0]。
解法一:
创建一个临时数组,将原数组中的不为0元素存放到临时数组中。再将临时数组中的所有元素赋给原始数组,原始数组中其他元素置0.
代码:
class Solution{
public:
void moveZeroes(vector<int>& nums){
vector<int>nonZeroesElements;
//move all the non not zero elements to the nonZeroesElements array
for(unsigned i=0;i<nums.size();i++){
if(nums[i]){
nonZeroesElements.push_back(nums[i]);
}
}
//move all the elements of nonZeroesElements to nums
for(int i=0;i<nonZeroesElements.size();i++){
nums[i] = nonZeroesElements[i];
}
//the rest elements have to be set as 0
for(int i=nonZeroesElements.size();i<nums.size();i++){
nums[i] = 0;
}
}
};
时间复杂度:O(n)
空间复杂度:O(n)
解法二:
设置一个临时变量K,用来指向非0元素在数组中所要存放的位置,K初始化为0。遍历数组,当nums[i]非0,则nums[k] = nums[i],k++,继续遍历数组。解法二和解法一雷同,只是将解法一中的临时数组取消,直接在原数组进行改动,这样更省空间。
代码
//second method
void moveZeroes2(vector<int>&nums){
//use a temp element k that points to the location
//where not zero element will place
int k = 0;
for(int i=0;i<nums.size();i++){//nums[0~k] place all the not zero element
if(nums[i]){//nums[i] is not zero
nums[k] = nums[i];
k++;
}
}
//in the array a, other elements have to be set as zero
for(int i=k;i<nums.size();i++){
nums[i] = 0;
}
}
时间复杂度:O(n)
空间复杂度:O(1)
解法三
创建一个临时变量k, k初始化为0. 遍历数组nums, nums[i]非0,交换nums[i]和nums[k],最后效果nums[0~k]皆非0,nums[k+1 ~ size-1]元素皆为0. 与上述两种方法的区别是,通过将元素进行了交换,而不是用非0元素直接覆盖原值,后续不需置0。
代码
//third method
void moveZeroes3(vector<int>& nums){
int k = 0;//nums[0~k] are not zero
for(int i=0;i<nums.size();i++){
if(nums[i]){//nums[i] is not zero
if(k!=i){
swap(nums[k],nums[i]);//swap nums[i] with nums[k]
k++;
}
else{
k++;//there is no need to swap
//at the same position with a not zero element
}
}
}
}
时间复杂度:O(n)
空间复杂度:O(1)