I want to check duplicate values in an array

前端 未结 4 1761
梦谈多话
梦谈多话 2021-01-29 09:18

Hi i\'m really glad to know this site to ask question. I have a problem that i made an array. And then i want to check matching values in the array. For example,



        
相关标签:
4条回答
  • 2021-01-29 09:44

    Pretty much. At least, is the simpliest method to do what you want. If you need to control the ocurrences or similar, maybe a Map type is more suitable for you.

    0 讨论(0)
  • 2021-01-29 09:48

    It depends on whether there are bounds on the size of the int's that can be on your array.

    If you can be sure (and check) that all elements in your array are limited to a relatively small range (say, between say 0 and 255), you can use a separate array of size MAXVAL-MINVAL to keep track of where in the array each element first appears. If this is the case, you can quickly check in O(n) (where n is the size of your array) whether (and even where) there are duplicates.

    It might look like something like this (caveat: I haven't checked or even compiled this code)

    #define COUNTOF(x) ( sizeof(x) / sizeof((x)[0]) )
    int i, flags[MAXVAL-MINVAL];
    
    for(i=0; i<COUNTOF(flags); i++) flags[i]=-1; // Initialize flags to 'not found'
    
    for(i=0; i<COUNTOF(array); i++) 
    {
        if (flags[array[i]-MINVAL]!=-1)   // Duplicate value found
          printf("Value %d was found in positions %d and %d\n",array[i], i, flags[array[i]-MINVAL]);
        else  // Value had not been found before
          flags[array[i]-MINVAL]=i;  // Keep track of where first seen
    }
    
    0 讨论(0)
  • 2021-01-29 09:48

    use something like:

    int matchCount = 0;
    for(int i = 0;i < (sizeof(array)/sizeof(int)); i++)
    {
        for( int j=0; j<(sizeof(array)/sizeof(int)); j++)
        {
            if( i != j ) // skip when both indexes point to same location
            {
                if( array[i] == array[j] )
                {
                    matchCount++;
                }
            }
        }
    }
    

    The above is for an array of integers. very similar code for arrays of other sized types

    will count matches twice, so divide final matchCount by 2

    0 讨论(0)
  • 2021-01-29 10:03

    How do you use the "qsort"?

    qsort(( void * )array, 5 , sizeof( data[0] ) , my_sort );
    

    my_sort is a function to create your own. For example,

    int my_sort( const void * a , const void * b ) {
        if( *( int * )a < *( int * )b ) {
            return -1;
        }
        else
        if( *( int * )a == *( int * )b ) {
            // You can check here.
    
            return 0;
        }
        return 1;
    }
    
    0 讨论(0)
提交回复
热议问题