给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
1.必须在原数组上操作,不能拷贝额外的数组。
2.尽量减少操作次数。
解法1:(自己的做法)
分三步:一:先统计有多少个非零数count。二:把count个非零数提到数组前面(i指针定位前面位置,j指针则遍历后面元素,遇到非零数就把它和nums[i]交换,且i++.重复上述操作,把所有非零数放到前面去)。三:把数组中剩余位置元素置0.
java:
class Solution {
public void moveZeroes(int[] nums) {
int n=nums.length;
int count =0;
for(int i=0;i<n;i++){
if(nums[i]!=0){
count+=1;
}
}
for(int i=0;i<count;i++){
if(nums[i]==0){
int j=i+1;
while(nums[j]==0&&j<n-1){
j++;
}
nums[i]=nums[j];
nums[j]=0;
}
}
for(int i=count;i<n;i++){
nums[i]=0;
}
}
}
解法1进阶版:
这是我在csdn上看到的大佬的做法,感觉我的思路跟他的一样,但大佬的代码简洁了许多。
void moveZeroes(vector<int>& nums) {
// Write your code here
int pos1 = 0;
int n = nums.size();
for(int i=0; i<n; i++)
{
if(nums[i] != 0)
{
if(i != pos1)
nums[pos1] = nums[i];
pos1++;
}
}
for(int i=pos1; i<n; i++)
nums[i] = 0;
}
};
解法1又进阶版:
思路一样,也是学习大佬的做法,代码是真的简洁!
class Solution {
public:
void moveZeroes(vector<int>& nums) {
for (int i = 0, j = 0; i < nums.size(); ++i) {
if (nums[i]) {
swap(nums[i], nums[j++]);
}
}
}
};
解法2:
思路有所不同,两个索引i和j,i从后往前遍历,遇到零算出i和j的差值,然后把后面的元素前移。貌似这样做移动的步骤有点多。
public void moveZeroes(int[] nums) {
int curIndex = nums.length - 1;
int lastIndex = nums.length - 1;
int count = 0;
while (curIndex >= 0) {
if (nums[curIndex] == 0) {
count = lastIndex - curIndex;
for (int i = 0; i < count; i++) {
nums[curIndex + i] = nums[curIndex + i + 1];
}
nums[lastIndex] = 0;
lastIndex--;
}
curIndex--;
}
}
BB一句:
简洁!!简洁!!学习!!