[LeetCode] 26. Remove Duplicates from Sorted Array - Java

wanuki·2023년 8월 23일
0

문제

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.

구현 전 예상 풀이

의사 코드

int idx = 1;

for(i = 1; i < nums.length; i++)
	int num1 = nums[idx - 1];
    int num2 = nums[i];
    
    if(num1 < num2)
    	nums[idx] = num2;
        idx++;
        
return idx;

구현 코드

int idx = 1;

for (int i = 1; i < nums.length; i++) {
    int num1 = nums[idx - 1];
    int num2 = nums[i];

    if (num1 < num2) {
        nums[idx] = num2;
        idx++;
    }
}

return idx;

결과

예전 풀이

int i = 1;
int target = 1;

for(i = 1; i < nums.length; i++){
    if(nums[i - 1] != nums[i]){
        nums[target] = nums[i];
        target++;
    }
}

return target;

26. Remove Duplicates from Sorted Array

profile
하늘은 스스로 돕는 자를 돕는다

0개의 댓글