How do I find the median of numbers in linear time using heaps?

前端 未结 7 954
谎友^
谎友^ 2020-12-04 06:59

Wikipedia says:

Selection algorithms: Finding the min, max, both the min and max, median, or even the k-th largest element can be done i

7条回答
  •  抹茶落季
    2020-12-04 07:10

    Store the first integer in the array and set a counter to 1. Then loop through the remaining integers in the vector. If the current integer in the array is the same as the one stored, the counter is increased by one, otherwise the counter is decreased by one. If the counter ever reaches zero, throw away the stored integer and replace it with the current integer in the array. When you finally have looped through all integers you are left with one candidate. You then need to loop through the array again and count the occurrence of the candidate to verify that this really is a dominator.

    static int FindDominator(int[] arr)
    {
    int counter = 1;
    int candidate = arr[0];
    for(int i = 1; i < n; i++)
    {
       if(arr[i] == candidate) counter++
        else 
       {
            counter--;
            if(counter == 0) { candidate = arr[i]; counter = 1; }
        }
    }
    counter = 0;
    for(int i = 0;  i < n; i++)
    {
        if(arr[i] == candidate) counter++;
    }
    if(counter > n / 2) return candidate;
    else return -1;
    }
    

提交回复
热议问题