-
[leetcode] 26. Remove Duplicates from Sorted Array알고리즘 2021. 11. 16. 22:29
Description
내림차순 정수 배열이 주어졌을때, 해당 배열에서 중복을 모두 제거 한 후 배열의 길이를 출력하는 문제
Input: arr = [1, 1, 2]
Output: [1, 2, _]
Input: arr = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]
Output: [0, 1, 2, 3, 4, _, _, _, _, _]
Success
두개의 변수를 사용하여 각각 다른 인덱스를 바라보게 한다. 두 변수가 가르키고 있는 인덱스의 값이 다르면 특정 변수가 가르키고 있는 인덱스에 값을 할당하여 중복이 제거될 수 있도록 한다.
class Solution { public int removeDuplicates(int[] nums) { int j= 0; for(int i=1; i<nums.length; i++) { if (nums[j] != nums[i]) { nums[j+1] = nums[i]; j++; } } return j+1; } }
출처
'알고리즘' 카테고리의 다른 글
[leetcode] 905. Sort Array By Parity (0) 2021.11.22 [leetcode] 283. Move Zeroes (0) 2021.11.19 [leetcode] Replace Elements with Greatest Element on Right Side (0) 2021.11.13 [leetcode] 941. Valid Mountain Array (0) 2021.11.12 [leetcode] Check If N and Its Double Exist (0) 2021.11.12