-
[leetcode] 27. Remove Element알고리즘 2021. 11. 22. 21:23
Description
정수 배열과 특정 값이 주어졌을때, 배열 안에 특정 값이 있다면 모두 제거하는 문제
Input: arr = [3, 2, 2, 3], val = 3
Output: [2, 2, _, _]
Input: arr = [0, 1, 2, 2, 3, 0, 4, 2], val = 2
Output: [0, 1, 4, 0, 3, _, _, _]
Success
두 개의 포인터 변수를 이용하여 인덱스를 순회하고 특정 값이 아닌 값들을 앞에 배치시킨다.
class Solution { public int removeElement(int[] nums, int val) { if (nums == null) return -1; int j=0; for (int i=0; i<nums.length; i++) { if (nums[i] != val) { nums[j] = nums[i]; j++; } } return j; } }
출처
'알고리즘' 카테고리의 다른 글
[leetcode] 905. Sort Array By Parity (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