Untitled

 avatar
unknown
plain_text
17 days ago
2.5 kB
3
Indexable
import java.util.Random;
import java.util.Arrays;

public class QuickSelect {
    public int[] findKLargestElements(int[] nums, int k) {
        if (k <= 0 || k > nums.length) {
            throw new IllegalArgumentException("k must be between 1 and nums.length");
        }

        int n = nums.length;

        // Find the (n - k)-th smallest element to partition the k largest elements
        quickSelect(nums, 0, n - 1, n - k);

        // Extract the last k elements (they are guaranteed to be the k largest)
        int[] result = Arrays.copyOfRange(nums, n - k, n);

        // Sort the k largest elements for clarity (optional)
        Arrays.sort(result);

        return result;
    }

    private void quickSelect(int[] nums, int left, int right, int k) {
        Random rand = new Random();

        while (left <= right) {
            int pivotIndex = left + rand.nextInt(right - left + 1);
            int finalPivotIndex = partition(nums, left, right, pivotIndex);

            if (finalPivotIndex == k) {
                return; // Found the (n - k)-th smallest element
            } else if (finalPivotIndex < k) {
                left = finalPivotIndex + 1; // Narrow down to the right subarray
            } else {
                right = finalPivotIndex - 1; // Narrow down to the left subarray
            }
        }
    }

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

        for (int i = left; i < right; i++) {
            // Change comparison to prioritize larger elements
            if (nums[i] < pivotValue) {
                swap(nums, i, storeIndex);
                storeIndex++;
            }
        }

        swap(nums, storeIndex, right); // Move pivot to its final position
        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 = {7, 10, 4, 3, 20, 15};
        int k = 3; // Find the 3 largest elements

        int[] result = qs.findKLargestElements(nums, k);
        System.out.println("K largest elements: " + Arrays.toString(result));
    }
}
Leave a Comment