Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums.
Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things:
•
Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums.
•
Return k.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int[] expectedNums = [...]; // The expected answer with correct length
int k = removeDuplicates(nums); // Calls your implementation
assert k == expectedNums.length;
for (int i = 0; i < k; i++) {
assert nums[i] == expectedNums[i];
}
Plain Text
복사
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [1,1,2]
Output: 2, nums = [1,2,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Plain Text
복사
Example 2:
Input: nums = [0,0,1,1,1,2,2,3,3,4]
Output: 5, nums = [0,1,2,3,4,_,_,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively.
It does not matter what you leave beyond the returned k (hence they are underscores).
Plain Text
복사
Constraints:
•
1 <= nums.length <= 3 * 104
•
100 <= nums[i] <= 100
•
nums is sorted in non-decreasing order.
먼저 문제를 읽어보면 nums 리스트가 주어지는데 이 리스트에는 중복을 허용한 정수형 타입의 요소들이 들어가있다. 그리고 문제가 원하는 것은 중복값을 제외한 요소들의 갯수 k를 반환하는 것이다.
해당 문제를 처음 읽어보았을 때는 꽤 간단해보였다. 하지만 이 문제는 특이하게 어떻게 채점을 할 것인지에 대한 설명까지 보여주고있다. 즉, 채점 기준을 명확히 알려준다. 그래서 채점 기준을 살펴보면 반환된 k만큼 루프를 돌며 expectedNums 배열안에 있는 요소들과 비교해서 전부 일치하면 정답 처리를 해준다.
여기서 필자가 눈치챈것은 입력값으로 주어지는 nums 배열에서 중복값이 있는 것은 제거하면서 값을 앞으로 땡겨주면 된다는 것이다. 문제에서 어짜피 k 이후의 인덱스번째에 위치해있는 값들은 전혀 상관이 없다고 하였다. 그 뜻은 k 번 이후에 있는 값들이야 어찌 되건 0부터 k까지의 값이 expectedNums 배열안에 있는 요소들과 같으면 된다는 것이다.
expectedNums 배열 안에는 아마 중복을 제거한 요소들이 정렬되어서 있을거라고 추측된다. 따라서 파라미터로 받은 nums 배열을 수정해야하는데…
nums 배열은 함수 내부에서 수정해야 한다. 처음에는 함수 내부에서 nums 배열을 수정해야 한다는 사실은 알았지만, 파라미터로 받은 배열을 내부에서 바꾼 것이 어떻게 함수 밖에서도 영향을 미칠 수 있는지가 궁금했다. 이에 대해 찾아본 결과, 자바에서 배열은 값 자체가 복사되어 전달되는 것이 아니라 배열 객체의 참조(reference)가 전달된다. 따라서 함수 내부에서 nums를 수정하면 이는 곧 참조된 동일한 배열 객체의 내용을 바꾸는 것이고, 그 결과 함수 외부의 nums에도 그대로 영향을 미치게 된다.