How to find the index of second largest element in an array collection?

后端 未结 3 606
攒了一身酷
攒了一身酷 2021-01-25 08:43

I have a function which calculates sum of money spent on each checkout on a counter, After calculation, i want to find the best two checkout counter, I am able to find the index

相关标签:
3条回答
  • 2021-01-25 09:15

    Don't make it complicated, it is simple:

    INDX = (-ARRAY).argsort()[:N]
    

    where N is the number of elements you are searching for, e.g. N=2 (two largest numbers) ARRAY is your numpy array which you are searching in, e.g. ARRAY=np.array[10.1,9,10,5,1,3] and, INDX is a list of the indices of the elements within the ARRAY. Obviously the length of INDX is equal to N.

    0 讨论(0)
  • 2021-01-25 09:20

    The second best is not sent only when you outperform the best.

    Example with 40, 60, 50, 30

    With your code, the fist time you set a best, is with 40. Then 60 replaces it an 40 becomes the second best. THen 50 arrives but it doesn't outperform the best so gets ignored as second best.

    You have to add an clause, to handle this case:

    ...
    if (sumM > maxmoney)   // as you already did
    {
        Secondbestcheckout=firstbestcheckout;
        firstbestcheckout = indexofmax+1;
        secondmaxmoney = maxmoney;   // <<NEW INSTRUCTION - of course, you'll need to create and init secondmaxmoney somewhere ;-)
        maxmoney = sumM;
        secondindex = Secondbestcheckout;
        indexofmax =firstbestcheckout;
    }
    else if (sumM > secondmaxmoney)       // NEW STATEMENT  
    {
        Secondbestcheckout= ...;       // as above, but unclear for me what the difference with secondinex is
        secondmaxmoney = maxmoney;     // update amount onf second best
        secondindex = i;               // or i+1 ?  Not clear if you start from 0 or from 1 
    }
    ...  // rest or your code
    
    0 讨论(0)
  • 2021-01-25 09:28

    If you can keep all the values in memory (i.e. if you have fewer than billions of checkouts), you can either use std::partial_sort to sort the two largest elements (but leave the rest unsorted), or you can use std::nth_element twice, once with 1 and once with 2. (In both cases, your predicate should be std::greater, I suppose.)

    If you need to process the values in a streaming fashion (i.e. with constant space), then you'll need to keep track of each order index separately, essentially similar to what you're attempting already. Boost.Accumulators may have some tools to simplify that task.

    0 讨论(0)
提交回复
热议问题