-
[leetcode] 283. Move Zeroes알고리즘 2021. 11. 19. 08:09
Description
정수 배열이 주어졌을때, 0이 아닌 요소를 앞으로 이동시키고 배열의 모든 0 은 끝으로 이동시킨다.
Input: arr = [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0 ,0]
Input: arr = [0]
Output: [0]
fail
두 개의 포인터 변수를 둔다.
0이 아닌 값들을 찾을 변수 i 와 앞에서부터 변경되어야 할 인덱스를 가르키는 변수 j를 두어 계속해서 0이 아닌 값들을 앞으로 이동시킨다. 결국 0인 값들은 뒤로 이동되고, 0이 아닌값들은 앞으로 이동된다.
class Solution { public void moveZeroes(int[] nums) { int j = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] != 0) { int temp = nums[j]; nums[j] = nums[i]; nums[i] = temp; j++; } } } }
출처
'알고리즘' 카테고리의 다른 글
[leetcode] 27. Remove Element (0) 2021.11.22 [leetcode] 905. Sort Array By Parity (0) 2021.11.22 [leetcode] 26. Remove Duplicates from Sorted Array (0) 2021.11.16 [leetcode] Replace Elements with Greatest Element on Right Side (0) 2021.11.13 [leetcode] 941. Valid Mountain Array (0) 2021.11.12