offer-数组中重复的数字

数组中重复的数字:

1.可用排序法(排序后就会知道重复数字)

时间复杂度O(nlogn)

空间复杂度

2.可用哈希表

时间复杂度 O(n)

空间复杂度O(n) //需要哈希表

3 .利用针对情况分析,下标法

时间复杂度O(n)

空间复杂度O(1)  //在当前数组操作

class Solution {
public:
    // 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) {
      //异常处理
       
        if (duplication==NULL||length<=0)
            return false;
       for(int i=0;i<length-1;i++) //剔除不满足条件的
       {
        if ( numbers[i]<=0||numbers[i]>=length)
            return false;       
       }
     
        
        for(int i=0;i<length-1;i++)
        {      
            while(numbers[i]!=i)  //循环的在判断
            {
               if(numbers[i]==numbers[numbers[i]])  //如果是这样 那么找到了重复的
               {
                   *duplication++=numbers[i];
                   return true;
               }
             //  swap(numbers[i],numbers[numbers[i]])
             int temp=numbers[i];
             numbers[i]=numbers[temp];

             numbers[temp]=temp;

            }
 
        }
      
        return false; //顺序排列  无重复数字
        
    
    }
};
原文地址:https://www.cnblogs.com/cgy1012/p/11364980.html