Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# ตรวจสอบว่าอาร์เรย์มีค่าซ้ำหรือไม่


ภาพรวม

ใช้ Dictionary<T, int> นับจำนวนครั้งที่แต่ละค่าปรากฏ เพื่อหาค่าที่ซ้ำ (duplicate)

อัลกอริทึม

  1. สร้าง Dictionary เพื่อนับความถี่
  2. วนลูปอาร์เรย์: ถ้าคีย์มีอยู่แล้ว เพิ่มนับ, ไม่มีเพิ่มใหม่ = 1
  3. ค่าที่นับ > 1 คือค่าซ้ำ

ตัวอย่างโค้ดเต็ม

using System;
using System.Collections.Generic;

namespace Demo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            int[] arr = { 89, 12, 56, 89 };
            var dict = new Dictionary();
            foreach (var item in arr)
            {
                if (dict.ContainsKey(item)) dict[item]++;
                else dict[item] = 1;
            }
            foreach (var kvp in dict)
                Console.WriteLine("{0} occurred {1} times", kvp.Key, kvp.Value);
        }
    }
}

ผลลัพธ์

89 occurred 2 times
12 occurred 1 times
56 occurred 1 times

วิธีอื่นๆ

  • LINQ: arr.GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g.Key)
  • HashSet<T>: if (!set.Add(item)) duplicates.Add(item); - O(n) memory efficient
  • Sort แล้วตรวจสอบติดกัน: Array.Sort(arr); for(i=1;i - O(n log n) no extra memory