Untitled

 avatar
unknown
plain_text
22 days ago
2.0 kB
2
Indexable
import java.util.Random;

public class QuickSelect {
    public int findKthLargest(int[] nums, int k) {
        int n = nums.length;
        // Convert k-th largest to index (0-based): n - k
        return quickSelect(nums, 0, n - 1, n - k);
    }

    private int quickSelect(int[] nums, int left, int right, int k) {
        // Choose a random pivot to optimize the partitioning process
        Random rand = new Random();
        int pivotIndex = left + rand.nextInt(right - left + 1);

        // Partition the array around the pivot and get its final position
        int finalPivotIndex = partition(nums, left, right, pivotIndex);

        if (finalPivotIndex == k) {
            return nums[finalPivotIndex]; // Found the k-th largest
        } else if (finalPivotIndex < k) {
            return quickSelect(nums, finalPivotIndex + 1, right, k); // Search right
        } else {
            return quickSelect(nums, left, finalPivotIndex - 1, k); // Search left
        }
    }

    private int partition(int[] nums, int left, int right, int pivotIndex) {
        int pivotValue = nums[pivotIndex];
        // Move pivot to the end
        swap(nums, pivotIndex, right);
        int storeIndex = left;

        // Move all elements smaller than pivot to the left
        for (int i = left; i < right; i++) {
            if (nums[i] < pivotValue) {
                swap(nums, i, storeIndex);
                storeIndex++;
            }
        }

        // Move pivot to its final position
        swap(nums, storeIndex, right);
        return storeIndex;
    }

    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }

    public static void main(String[] args) {
        QuickSelect qs = new QuickSelect();
        int[] nums = {3, 2, 1, 5, 6, 4};
        int k = 2; // Find the 2nd largest element
        System.out.println("K-th largest element: " + qs.findKthLargest(nums, k)); // Output: 5
    }
}
Editor is loading...
Leave a Comment