-
[leetcode] 905. Sort Array By Parity알고리즘 2021. 11. 22. 18:19
Description
정수 배열이 주어졌을때, 짝수인 요소를 앞으로 이동시켜라
Input: arr = [3, 1, 2, 4]
Output: [2, 4, 3, 1]
Input: arr = [0]
Output: [0]
Success
두 개의 포인터 변수를 둔다.
인덱스를 돌며 짝수인 값을 앞으로 이동시킨다. 이동이 된 후에는 그 다음 인덱스를 가리킬 수 있도록 j 값을 1씩 증가시킨다.
class Solution { public int[] sortArrayByParity(int[] nums) { int j=0; for (int i=0; i<nums.length; i++) { if (nums[i] % 2 == 0) { swap(nums, i, j); j++; } } return nums; } private void swap (int[] nums, int i, int j) { int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } }
출처
'알고리즘' 카테고리의 다른 글
[leetcode] 27. Remove Element (0) 2021.11.22 [leetcode] 283. Move Zeroes (0) 2021.11.19 [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