C++編程求數組中重復的數字


題目:在一個長度為n的數組里的所有數字都在0到n-1的范圍內。 數組中某些數字是重復的,但不知道有幾個數字是重復的。也不知道每個數字重復幾次。請找出數組中任意一個重復的數字。 例如,如果輸入長度為7的數組{2,3,1,0,2,5,3},那么對應的輸出是第一個重復的數字2。

思路:先將數組從小到大排列,然后一次比較相鄰的兩個數,若有重復,就將第一個重復的數字輸出。

代碼:

// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number

// Return value: true if the input is valid, and there are some duplications in the array number

// otherwise false

bool duplicate(int numbers[], int length, int* duplication)

{
  sort(numbers,numbers+length);
  int n=0;
  *duplication=-1;
  if(numbers==NULL||length==0)
    return false;
  for(int i=0;i<length-1;i++)
  {
    if(numbers[i]==numbers[i+1])
    {
      *duplication=numbers[i];
      break;
    }
  }
  if(*duplication!=-1)
  {
    cout<<*duplication<<endl;
    return true;
  }
  else return false;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM