Accepted Java Solution Using Heapsort


  • 6
    C
    public class Solution 
    {
        private static int L;
        public int findKthLargest(int[] nums, int k) 
        {
            heapSort(nums);
            return nums[nums.length - k];
        }
        
        private void heapSort(int[] nums)
        {
           buildHeap(nums);
           for(int i = L;i >=1; i--)
           {
               swap(nums, 0, i);
               L = L - 1;
              heapify(nums, 0);
           }
        }
        
        private void buildHeap(int[] nums)
        {
            L = nums.length-1;
            for(int i = L/2; i >=0; i--)
                heapify(nums, i);
        }
        
        //max-heap
        private void heapify(int[] nums, int i)
        {
            int l = 2 * i;
            int r = l + 1;
            int largest = i;
            if((l <= L) && (nums[l] > nums[largest]))
                largest = l;
            if((r <= L) && (nums[r] > nums[largest]))
                largest = r;
            if(largest != i)
            {
                swap(nums, i, largest);
                heapify(nums, largest);
            }
        }
        
        private void swap(int[] arr, int a, int b)
        {
            int temp = arr[a];
            arr[a] = arr[b];
            arr[b] = temp;
        }
    }

Log in to reply
 

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