本篇同步發布於Blog:[解題] LeetCode - 283 Move Zeroes
LeetCode
283 - Move Zeroes
https://leetcode.com/problems/move-zeroes/
輸入1個陣列nums,將有0的元素都移到陣列最後面,而前面非0的元素相對順序要和原本一樣。
比如範例輸入的[0,1,0,3,12],移動完後變成[1,3,12,0,0]。
使用一個變數lastZeroIndex,用來記錄0的位置。從索引值最小開始檢查每個nums的元素 ,只要是非0就做與nums[lastZeroIndex]交換的動作,這動作會把0一直往後移。
以範例輸入[0,1,0,3,12]:
所以最終答案是[1, 3, 12, 0, 0]
難度為Easy
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int n = nums.size();
int lastZeroIndex = 0;
for(int i = 0 ; i < n;++i){
if(nums[i] != 0){
swap(nums[i], nums[lastZeroIndex++]);
}
}
}
};
int main() {
Solution sol;
vector<int> nums{0,1,0,3,12};
sol.moveZeroes(nums);
for(int num : nums){
cout << num << " ";
}
return 0;
}
using System;
namespace LeetCode283
{
public class Program
{
public class Solution {
public static void Swap<T> (ref T lhs, ref T rhs) {
T temp = lhs;
lhs = rhs;
rhs = temp;
}
public void MoveZeroes(int[] nums) {
int size = nums.Length;
int lastZeroIndex = 0;
for(int i = 0 ; i < size;++i){
if(nums[i] != 0){
Swap<int>(ref nums[i], ref nums[lastZeroIndex++]);
}
}
}
}
public static void Main()
{
int[] nums = new int[]{0,1,0,3,12};
Solution sol = new Solution();
sol.MoveZeroes(nums);
foreach(int num in nums){
Console.Write(" " + num);
}
Console.Read();
}
}
}
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%2B%2B/200-299/283.cpp
https://github.com/u8989332/ProblemSolving/blob/master/LeetCode/C%23/200-299/283.cs