Appearance
Move all zeroes to end of array
Problem Description
Given an integer array A, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Problem Constraints
Input Format
First argument is array of integers A.
First argument is array of integers A.
Output Format
Return an array of integers which satisfies above property.
Return an array of integers which satisfies above property.
Example Input
Input 1:
A = [0, 1, 0, 3, 12]
Input 2:
A = [0]
Input 1:
A = [0, 1, 0, 3, 12]
Input 2:
A = [0]
Example Output
Ouput 1:
[1, 3, 12, 0, 0]
Ouput 2:
[0]
Ouput 1:
[1, 3, 12, 0, 0]
Ouput 2:
[0]
Example Explanation
Explanation 1:
Shift all zeroes to the end.
Explanation 2:
There is only one zero so no need of shifting.
Explanation 1:
Shift all zeroes to the end.
Explanation 2:
There is only one zero so no need of shifting.
Solution
TIP
Array Iteration.
swift
import Foundation
class Solution {
func solve(_ A: inout [Int]) -> [Int] {
var i = 0
for v in A {
if v != 0 {
A[i] = v
i += 1
}
}
if i < A.count {
for j in i..<A.count{
A[j] = 0
}
}
return A
}
}
import Foundation
class Solution {
func solve(_ A: inout [Int]) -> [Int] {
var i = 0
for v in A {
if v != 0 {
A[i] = v
i += 1
}
}
if i < A.count {
for j in i..<A.count{
A[j] = 0
}
}
return A
}
}