plain c code, beats 15.9%


  • 0
    D
    // Get index of minimum number in the array *in*
    int findMinIndex(int *in, int len) {
        int min = INT_MAX;
        int j = 0;
        for (int i = 0; i < len; i++) {
            if (min > in[i]) {
                j = i;
                min = in[i];
            }
        }
        return j;
    } 
    
    int findKthLargest(int* nums, int numsSize, int k) {
        // Array of size *k* to store k largest numbers we encounted 
        // when scan through the array, Initialize array to INT_MIN
        int kLen[k];
        for (int i = 0; i < k; i++) {
            kLen[i] = INT_MIN;
        }
        // If encounter a number in *nums*  that less than the minimum in *kLen*
     store this number in kLen[index of minimum number].
        int n;
        for (int i = 0; i < numsSize; i++) {
            n = findMinIndex(kLen, k);
            if (kLen[n] < nums[i]) {
                kLen[n] = nums[i];
            }
        }
        
        // Get the kth largest
        int res = kLen[0];
        for (int i = 0; i < k; i++) {
            if (res > kLen[i]) {
                res = kLen[i];
            }
        }
        
        return res;
    }
    

    Time Complexity: O(numsSize * k)
    Space Complexity: O(k)


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.