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.
給定一個數(shù)組數(shù)字讶隐,編寫一個函數(shù)將所有的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.
不能重寫一個數(shù)組蟹略,在原始數(shù)組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
# 當出現(xiàn)不為零的與零的交換位置
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++;
}
}
}
};