Repeated numbers in the algorithm array

All numbers in an array nums of length n are in the range of 0~n-1. Some numbers in the array are repeated, but I don't know how many numbers are repeated, nor do I know how many times each number is repeated. Please find any duplicate number in the array.

Example 1:

enter:

[2, 3, 1, 0, 2, 5, 3]

Output: 2 or 3

Algorithm 1: Double loop to check whether the current number exists in the following numbers, if it exists, find it, if it does not exist, continue to find the next one until the end. Time complexity O(n^2), space complexity O(1)

 int FindRepeatNumber(int* nums, int numsSize)//O(n^2),O(1)  

 {
    
      

     for(int i=0;i<numsSize;i++)  

     {
    
      

         for(int j=i+1;j<numsSize;j++)//在i后面找,当前数字是否存在  

         {
    
      

             if(nums[i] == nums[j])  

                 return nums[i];  

         }          

    }  

    return -1;  

}

Algorithm 2: Space is exchanged for time. According to the characteristics of the data value range (0~n-1), each data can be stored in the same subscript as its own value, for example, the number 2 is stored in the subscript 2 to construct a hash table During the storage process, if the data stored in the subscript is the same as the current one, it will be found. Time complexity O(n), space complexity O(1)

 int FindRepeatNumber(int* nums, int numsSize)//O(n),O(1)  

 {
    
      

     int tmp;  

     int x;//存放nums[i]的数据  

     for(int i=0;i<numsSize;i++)  

     {
    
      

         x = nums[i];  

         if(x==nums[x] && x!=i)//x!=i是去除本身就在自己位置的值.例如 0,3,3,那么0不算  

         {
    
      

            return x;              

        }     

        else  

        {
    
      

            tmp = nums[i];  

            nums[i] = nums[x];  

            nums[x] = tmp;  

        }  

    }  

    return -1;  

}  

Guess you like

Origin blog.csdn.net/Gunanhuai/article/details/109146473