배열은 이미 정렬되어 있으므로 두 개의 포인터 ii와 jj를 유지할 수 있습니다. 여기서 ii는 느린 주자이고 jj는 빠른 주자입니다. nums[i] =nums[j]nums[i]=nums[j]인 한, 중복을 건너뛰기 위해 jj를 증가시킵니다.
nums[j] !=nums[i]를 만나면 중복 실행이 종료되었으므로 해당 값을 nums[i + 1]nums[i+1]에 복사해야 합니다. 그런 다음 ii가 증가하고 jj가 배열의 끝에 도달할 때까지 동일한 프로세스를 다시 반복합니다.
시간 복잡도 - O(N)
예시
using System;
namespace ConsoleApplication{
public class Arrays{
public int RemoveDuplicatesFromSortedArrayAndReturnLength(int[] arr){
int index = 1;
for (int i = 0; i < arr.Length - 1; i++){
if (arr[i] != arr[i + 1]){
arr[index] = arr[i + 1];
index++;
}
else{
continue;
}
}
return index;
}
}
class Program{
static void Main(string[] args){
Arrays a = new Arrays();
int[] arr = { 0, 0, 1, 1, 1, 2, 2, 3, 3, 4 };
int res = a.RemoveDuplicatesFromSortedArrayAndReturnLength(arr);
Console.WriteLine(res);
Console.ReadLine();
}
}
} 출력
5