leetcode Day 4
题目:
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.
给定一个数组数字,编写一个函数将所有的0移动到它的末尾,同时保持非零元素的相对顺序。
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.
不能重写一个数组,在原始数组nums上操作
1. python
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
j= 0
for i in range(len(nums)):
if nums[i]!=0:
#nums[i]=nums[j] #错误
#nums[j]=nums[i]
nums[i],nums[j]=nums[j],nums[i]
j+=1
# 当出现不为零的与零的交换位置
2. C++
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int j=0;
for (int i=0;i<nums.size();i++)
{
if (nums[i]!=0){
swap(nums[i],nums[j]);
j++;
}
}
}
};