-
[알고리즘] #Move Zeroes■ Algorithm 2019. 7. 8. 00:01
출처 : https://leetcode.com/problems/move-zeroes/
Move Zeroes - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
문제
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:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
풀이
이 문제를 풀 때 주의할 점은 배열 복사본을 만들지 않고, 주어진 배열 nums를 사용해서 풀어야한다는 것이다.
그래서 마지막에 리턴 값 없이 nums 배열 값을 바꿔 놓아야 한다.
nums를 순회하면서 0이 아닌 경우에는 nums의 0번째 요소 값을 i번 째 요소 값으로 바꾼다. 그리고 idx 변수에 1을 추가한다.
순회가 끝나고 나면 idx는 nums에 0이 아닌 수의 갯수만큼 추가되었을 것이다.
그래서 그 이후부터 nums.length-1번째 요소까지 0으로 바꾼다.
'■ Algorithm' 카테고리의 다른 글
[알고리즘] #Majority Element (0) 2019.07.18 [알고리즘] #Merge Two Sorted Lists (0) 2019.07.12 [알고리즘] #Reverse Linked List (0) 2019.07.07 [알고리즘] #Invert Binary Tree (0) 2019.07.07 [알고리즘] #Single Number (0) 2019.07.06