Problem solving/Algorithms

[LeetCode] 26. Remove Duplicates from Sorted Array (C#)

Young_A 2021. 1. 29. 14:28

LeetCode - Problems - Algorithms - 26. Remove Duplicates from Sorted Array

Problem Description

My Solution (C#)

public class Solution {
    public int RemoveDuplicates(int[] nums) {
        if (nums.Length == 0)
            return 0;
        int index = 0;
        for (int i = 1; i < nums.Length; i++)
        {
            if (nums[index] != nums[i])
            {
                nums[++index] = nums[i];
            }
        }
        return ++index;
    }
}

C#의 regular array는 길이를 조절할 수 없는 array이다.

그러다 문제는 array의 값을 조정하라고 되어있고, return 값은 오직 array의 길이를 요구하고 있다.

또한 문제는 Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 라고 명시하고 있으므로 새로운 array를 만들어서 값을 저장하면 안된다.

int[] nums은 references로서 method로 패스된 값이므로, nums의 elements 값을 변경한 뒤, 필요한 값의 길이만 반환함으로서 길이를 조절한 것과 같은 효과를 원하는 것 같다.

(test harness가 for (int i = 0; i < RemoveDuplicates(nums); i++)과 같은 반복문을 포함하지 않을까 한다.)

 

아무튼 nums의 길이가 0인지 체크하여 맞다면 0을 리턴하여 종료한다.

 

아니라면 중복되지 않은 값이 저장된 마지막 위치를 확인하기 위한 변수 index를 0으로 initialize 해준다. (첫번째 요소는 중복되지 않았으므로)

for 반복문을 열어서 두번째 element(index값이 1)부터 마지막 element까지 확인할 수 있도록 하고,

중복되지 않은 값이 저장된 위치(index)의 값(nums[index])와 현재 값(index[i])이 같지 않다면, 그 다음 위치(++index)에 현재 값(index[i])를 저장한다.

 

반복문이 끝난 후 저장된 index에 1을 더한 값을 return 한다. (문제는 마지막 요소의 index 값을 원하는 것이 아니라, 마지막 요소까지의 길이를 원하므로)