알고리즘/해결

LeetCode283. Move Zeroes

언클린 2020. 4. 12. 09:09
728x90

1. 문제(원본)

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.

Example:

Input: [0,1,0,3,12] Output: [1,3,12,0,0]

Note:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.

2. 문제

임의의 배열에서 인덱스 0을 뒤로 옮겨라

3. 나의 답

class Solution {

    func moveZeroes(_ nums: inout [Int]) {

        for element in nums where element == 0 {

            if let index = nums.firstIndex(of: element) {

                nums.remove(at: index)

                nums.append(0)

            }

        }

    }

}

4. 다른 유저의 답

#1

class Solution {

    func moveZeroes(_ nums: inout [Int]) {

        guard nums.count > 1 else { return }

        var zeroPtr = 0

        var nonZeroPtr = 0

 

        for num in nums{

            if num != 0{

                swap(&nums, zeroPtr, nonZeroPtr)

                zeroPtr += 1

            }

            nonZeroPtr += 1

        }

    }

 

    func swap(_ nums: inout [Int], _ index1: Int, _ index2: Int ){

        let temp = nums[index1]

        nums[index1] = nums[index2]

        nums[index2] = temp

    }

}

 

#2

func moveZeroes(_ nums: inout [Int]) {

       let count = nums.count

       nums = nums.filter { $0 != 0}

       for _ in 0 ..< (count - nums.count) { nums.append(0) }

}

5. 마무리

이번 문제에서는 정렬 법을 사용해서 하기 보다는 좀 더 빠르게 배열을 재 구축하는 방법으로 진행하였다. 배열의 크기의 변화는 없고 0만 뒤로 보내면 되는 것이기 때문에 해당 인덱스가 0이면 삭제하여 새로운 0을 대입하는 방법으로 만들었다.

728x90

'알고리즘 > 해결' 카테고리의 다른 글

LeetCode412. Fizz Buzz  (0) 2020.04.12
LeetCode868. Binary Gap  (0) 2020.04.12
LeetCode867. Transpose Matrix  (0) 2020.04.05
LeetCode1046. Last Stone Weight  (0) 2020.04.05
LeetCode344. Reverse String  (0) 2020.03.31