Given an integer array nums, 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.
Example 1:
Input: nums = [0,1,0,3,12]
Output: [1,3,12,0,0]
Example 2:
Input: nums = [0]
Output: [0]
Constraints:
Follow up: Could you minimize the total number of operations done?
func moveZeroes(nums []int) {
if len(nums) <= 1 {
return
}
wp := 0
for j, v := range nums {
if j == wp && v != 0 {
wp++
} else if v != 0 {
nums[wp], nums[j] = v, 0
wp++
}
}
}
func moveZeroes(nums []int) {
lastzero := 0
for i := 0; i < len(nums); i++ {
if nums[i] != 0 {
nums[lastzero] = nums[i]
lastzero++
}
}
for i := lastzero; i < len(nums); i++ {
nums[i] = 0
}
}
func moveZeroes(nums []int) {
index:=0
for i:=0;i<len(nums);i++ {
if nums[i]!=0 {
nums[index], nums[i] = nums[i], nums[index]
index++
}
}
func moveZeroes(nums []int) {
numZeros := 0
i := 0
for _, num := range(nums) {
if num == 0 {
numZeros++
} else {
nums[i] = num
i++
}
}
numNonZeros := len(nums) - numZeros
for j := numNonZeros; j < len(nums); j++ {
nums[j] = 0
}
}
func swap(nums []int, i int, j int) {
tmp := nums[i]
nums[i] = nums[j]
nums[j] = tmp
}
func moveZeroes(nums []int) {
i := 0
for _, num := range nums {
if num != 0 {
nums[i] = num
i++
}
}
for j := i; j < len(nums); j++ {
nums[j] = 0
}
}
func moveZeroes(nums []int) {
n:=0
for i,elem := range nums {
if(elem != 0){
if(nums[n] == 0){
nums[i],nums[n] = 0, elem
}
n++
}
}
}
func moveZeroes(nums []int) {
n := 0
for i, elem := range nums {
if elem != 0 {
nums[i], nums[n] = 0, elem
n++
}
}
}
func moveZeroes(nums []int) {
length := len(nums)
//right := length
for i := 0; i < length ; i++ {
for j := 0; j < length -1; j++ {
if nums[j] == 0 {
nums[j], nums[j+1] = nums[j+1], nums[j]
}
}
}
}
func moveZeroes(nums []int) {
z := 0
for i, n := range nums {
if n != 0 {
x := nums[i]
nums[i] = nums[z]
nums[z] = x
z++
}
}
}
func Switch(nums []int, i int, j int) {
nums[i], nums[j] = nums[j], nums[i]
}
func moveZeroes(nums []int) {
nonZero := make([]int, len(nums))
var index int
for _, num := range nums {
if num != 0 {
nonZero[index] = num
index++
}
}
for i := range nums {
nums[i] = nonZero[i]
}
}
Array101 Remove Element (0) | 2022.03.15 |
---|---|
Array 101 Sort Array By Parity (0) | 2022.03.15 |
Arrays 101 Code from Java to Go(A Better Repeated Deletion Algorithm - Answer) (0) | 2022.03.10 |
Array101 Remove Duplicates from Sorted Array (0) | 2022.03.06 |
Arrays 101 Code from Java to Go(A Better Repeated Deletion Algorithm - Intro) (0) | 2022.03.06 |
댓글 영역