Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.
정렬된 배열 nums
가 주어질 때, 주어진 배열에서 중복된 값을 제거해서 각 요소가 한번씩만 나오는 배열의 길이를 반환하라.
Input: nums = [1,1,2]
Output: 2, nums = [1,2]
Explanation: Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the returned length.
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 length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length.
이번 문제도 새로운 배열을 만들지 않고 주어진 배열을 사용해서 풀어야 하는 문제다.
class Solution {
public int removeDuplicates(int[] nums) {
if(nums.length == 0 || nums == null) return 0;
int len = 1;
for (int i = 1; i < nums.length; i++){
if (nums[len-1]!=nums[i]){
nums[len]=nums[i];
len++;
}
}
return len;
}
}