อาร์เรย์ได้รับการเรียงลำดับแล้ว เราสามารถใช้ two pointers ii และ jj โดย ii เป็น slow-runner ในขณะที่ jj เป็น fast-runner ตราบใดที่ nums[i] = nums[j] เราเพิ่ม jj เพื่อข้ามค่าซ้ำ
เมื่อเราพบ nums[j] != nums[i] ช่วงค่าซ้ำจบลง เราต้องคัดลอกค่าของมันไปที่ nums[i + 1] ii จึงถูกเพิ่มขึ้นและเราทำกระบวนการเดิมซ้ำจนกว่า jj จะถึงปลายอาร์เรย์
Time complexity - 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