Algorithm to find two repeated numbers in an array, without sorting

前端 未结 24 2162
南方客
南方客 2020-11-28 06:58

There is an array of size n (numbers are between 0 and n - 3) and only 2 numbers are repeated. Elements are placed randomly in the array.

E.g. in {2, 3, 6, 1, 5, 4

24条回答
  •  不知归路
    2020-11-28 07:24

    You can use simple nested for loop

     int[] numArray = new int[] { 1, 2, 3, 4, 5, 7, 8, 3, 7 };
    
            for (int i = 0; i < numArray.Length; i++)
            {
                for (int j = i + 1; j < numArray.Length; j++)
                {
                    if (numArray[i] == numArray[j])
                    {
                       //DO SOMETHING
                    }
                }
    

    *OR you can filter the array and use recursive function if you want to get the count of occurrences*

    int[] array = { 1, 2, 3, 4, 5, 4, 4, 1, 8, 9, 23, 4, 6, 8, 9, 1,4 };
    int[] myNewArray = null;
    int a = 1;
    
     void GetDuplicates(int[] array)
        for (int i = 0; i < array.Length; i++)
                {
                    for (int j = i + 1; j < array.Length; j++)
                    {
                        if (array[i] == array[j])
                        {
                              a += 1;
                        }
                    }
                    Console.WriteLine(" {0} occurred {1} time/s", array[i], a);
    
                    IEnumerable num = from n in array where n != array[i] select n;
                     myNewArray = null;
                     a = 1;
                     myNewArray = num.ToArray() ;
    
                     break;
    
                }
                 GetDuplicates(myNewArray);
    

提交回复
热议问题