Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Cách xóa trùng lặp từ mảng đã sắp xếp và trả về độ dài C#

Mảng đã sắp xếp, dùng hai con trỏ i (chậm) và j (nhanh). Khi nums[i] = nums[j], tăng j để bỏ qua trùng lặp. Khi nums[j] != nums[i], kết thúc chuỗi trùng, copy giá trị vào nums[i+1], tăng i, lặp lại cho đến khi j hết mảng.

Độ phức tạp thời gian - O(N)

Ví dụ

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();
        }
    }
}

Kết quả

5

Giải thích: Tương tự bài trước nhưng chỉ trả về độ dài mảng sau khi xóa trùng (5). Mảng gốc được sửa đổi in-place, 5 phần tử đầu là {0,1,2,3,4}. Phù hợp LeetCode style "remove duplicates from sorted array".