mardi 26 juin 2018

I find a bug in Leetcode 215. Kth Largest Element in an Array

I write code for leetcode 215 Kth Largest Element in an Array

Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

int partition(vector<int>& nums, int start, int end)
{
    uniform_int_distribution<int> distribution(start, end);
    default_random_engine generator;
    int pivotIdx = distribution(generator);
    int pivot = nums[pivotIdx];
    std::swap(nums[pivotIdx], nums[end - 1]);

    int i = start;
    for (int j = start; j < end; ++j)
    {
        if (nums[j] < pivot)
        {
            std::swap(nums[i], nums[j]);
            ++i;
        }
    }

    std::swap(nums[i], nums[end - 1]);

    return i;
}


int findKthLargest(vector<int>& nums, int k)
{
    int size = (int)nums.size();

    int tempIdx = size - k;

    int start = 0;
    int end = size;
    while (start < end)
    {
        int pivotIdx = partition(nums, start, end);

        if (tempIdx < pivotIdx)
        {
            end = pivotIdx;
        }
        else if (tempIdx > pivotIdx)
        {
            start = pivotIdx + 1;
        }
        else
        {
            return nums[tempIdx];
        }
    }

    return -1;
}

nums = { 3, 2, 1, 5, 6, 4 }, k = 2,

in my computer, return 6, is wrong!

but online, return 5, is correct, is Accepted! Why?




Aucun commentaire:

Enregistrer un commentaire