- 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.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Solution_01:
# include <iostream>
# include <vector>
using namespace std;
class Solution{
public:
// vector是一个能够存放任意类型的动态数组
// 这个方法的空间复杂度为o(n),因为开辟了一个新的数组用于存放非0值
void moveZeroes(vector<int>& nums){
vector<int> nonZeroElements;
for (int i = 0; i < nums.size(); i++)
if ( nums[i] )
nonZeroElements.push_back( nums[i] );
for (int i = 0; i < nonZeroElements.size(); i++)
nums[i] = nonZeroElements[i];
for (int i = nonZeroElements.size(); i < nums.size(); i++)
nums[i] = 0;
}
};
int main(){
int arr[] = {0, 1, 0, 3, 12};
vector<int> vec(arr, arr + sizeof(arr)/sizeof(int) );
Solution().moveZeroes( vec );
for (int i = 0; i < vec.size(); i++) {
cout<<vec[i]<<" ";
}
cout<<endl;
return 0;
}
Solution_02
# include <iostream>
# include <vector>
using namespace std;
class Solution{
public:
// 时间复杂度O(n)
// 空间复杂度O(1)
void moveZeroes(vector<int>& nums) {
int k = 0; // nums中, [0...k)的元素均为非0元素
// 遍历到第i个元素后,保证[0...i]中所有非0元素
// 都按照顺序排列在[0...k)中
// 同时,[k...i]为0
for (int i = 0; i < nums.size(); i++)
if( nums[i] )
if( i != k )
swap( nums[k++], nums[i] );
else
k++;
}
};
int main(){
int arr[] = {0, 1, 0, 3, 12};
vector<int> vec(arr, arr + sizeof(arr)/sizeof(int) );
Solution().moveZeroes( vec );
for (int i = 0; i < vec.size(); i++) {
cout<<vec[i]<<" ";
}
cout<<endl;
return 0;
}
总结:第一种方法新开辟了内存空间。第二种方法不需要新的空间,而且逻辑简单。有时候自己手动模拟一下,就会发现比较好的解答。