283. Move Zeroes
Дан entier tableau nums. Переместите все нули в конец tableauа, сохраняя относительный порядок ненулевых elementов.
Обратите внимание, что вы должны сделать это на месте, не создавая копию tableauа.
Exemple:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
C# solution
correspondant/originalpublic class Solution {
public void MoveZeroes(int[] nums) {
int lastNonZeroFoundAt = 0;
for (int cur = 0; cur < nums.Length; cur++) {
if (nums[cur] != 0) {
int temp = nums[lastNonZeroFoundAt];
nums[lastNonZeroFoundAt] = nums[cur];
nums[cur] = temp;
lastNonZeroFoundAt++;
}
}
}
}
C++ solution
brouillon automatique, à relire avant soumission#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public void MoveZeroes(vector<int>& nums) {
int lastNonZeroFoundAt = 0;
for (int cur = 0; cur < nums.size(); cur++) {
if (nums[cur] != 0) {
int temp = nums[lastNonZeroFoundAt];
nums[lastNonZeroFoundAt] = nums[cur];
nums[cur] = temp;
lastNonZeroFoundAt++;
}
}
}
}
Java solution
correspondant/originalclass Solution {
public void moveZeroes(int[] nums) {
int lastNonZeroFoundAt = 0;
for (int cur = 0; cur < nums.length; cur++) {
if (nums[cur] != 0) {
int temp = nums[lastNonZeroFoundAt];
nums[lastNonZeroFoundAt] = nums[cur];
nums[cur] = temp;
lastNonZeroFoundAt++;
}
}
}
}
JavaScript solution
correspondant/originalvar moveZeroes = function(nums) {
let lastNonZeroFoundAt = 0;
for (let cur = 0; cur < nums.length; cur++) {
if (nums[cur] != 0) {
[nums[lastNonZeroFoundAt], nums[cur]] = [nums[cur], nums[lastNonZeroFoundAt]];
lastNonZeroFoundAt++;
}
}
};
Python solution
correspondant/originalclass Solution:
def moveZeroes(self, nums: List[int]) -> None:
lastNonZeroFoundAt = 0
for cur in range(len(nums)):
if nums[cur] != 0:
nums[lastNonZeroFoundAt], nums[cur] = nums[cur], nums[lastNonZeroFoundAt]
lastNonZeroFoundAt += 1
Go solution
correspondant/originalfunc moveZeroes(nums []int) {
lastNonZeroFoundAt := 0
for cur := 0; cur < len(nums); cur++ {
if nums[cur] != 0 {
nums[lastNonZeroFoundAt], nums[cur] = nums[cur], nums[lastNonZeroFoundAt]
lastNonZeroFoundAt++
}
}
}
Algorithm
Инициализация указателей:
Инициализируйте два указателя: lastNonZeroFoundAt для отслеживания позиции последнего ненулевого elementа и cur для итерации по tableauу.
Итерация и обмен elementами:
Итерируйтесь по tableauу с помощью указателя cur.
Если текущий element ненулевой, поменяйте его местами с elementом, на который указывает lastNonZeroFoundAt, и продвиньте указатель lastNonZeroFoundAt.
Завершение итерации:
Повторяйте шаг 2 до конца tableauа. В итоге все нули будут перемещены в конец tableauа, сохраняя относительный порядок ненулевых elementов.
😎
Vacancies for this task
offres actives with overlapping task tags are affichés.