-
[leetcode] 26. Remove Duplicates from Sorted Array카테고리 없음 2021. 11. 10. 08:06
Description
내림차순으로 정렬된 배열이 주어졌을때 배열 안에 중복된 값들을 제거하는 문제. 단, 새로운 배열 추가 없이 기존 배열에서 중복이 제거되어야 한다.
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Success
cnt 라는 변수를 하나 두고 for문이 적용된 i 변수의 인덱스의 값과 cnt 변수의 인덱스 값을 비교하여 다른 경우에만 앞에서부터 새롭게 할당시킨다.
class Solution { public int removeDuplicates(int[] nums) { if (nums == null) return -1; int cnt=0; for(int i=0; i<nums.length; i++) { if(nums[i] != nums[cnt]) { cnt++; nums[cnt] = nums[i]; } } return cnt+1; } }
출처