Easy
231983FavoriteShare
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]
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
利用stable_sort:
C++:
/*
* @Author: SourDumplings
* @Date: 2019-09-04 21:47:43
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/move-zeroes/
*
*/
class Solution
{
public:
void moveZeroes(vector<int> &nums)
{
stable_sort(nums.begin(), nums.end(), [](const int &i1, const int &i2) {
if (i1 != 0 && i2 == 0)
{
return true;
}
return false;
});
}
};
移位法:
C++:
/*
* @Author: SourDumplings
* @Date: 2019-09-05 21:45:54
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/move-zeroes/
*/
class Solution
{
public:
void moveZeroes(vector<int> &nums)
{
int n = nums.size();
int j = 0;
for (int i = 0; i < n; i++)
{
if (nums[i] != 0)
{
nums[j++] = nums[i];
}
}
fill(nums.begin() + j, nums.end(), 0);
}
};
Java:
import java.util.Arrays;
/*
* @Author: SourDumplings
* @Date: 2019-09-05 21:51:58
* @Link: https://github.com/SourDumplings/
* @Email: changzheng300@foxmail.com
* @Description: https://leetcode.com/problems/move-zeroes/
*/
class Solution
{
public void moveZeroes(int[] nums)
{
int n = nums.length;
int j = 0;
for (int i = 0; i < n; i++)
{
if (nums[i] != 0)
{
nums[j++] = nums[i];
}
}
Arrays.fill(nums, j, n, 0);
}
}