My merge sort solution Java 5ms

  • 1
    public class Solution {
        public int findKthLargest(int[] nums, int k) {
            int[] sortedArray = mergeSort(nums,0,nums.length-1);
            return sortedArray[sortedArray.length-k];
        public int[] mergeSort(int[] nums,int left,int right){
                int[] result = new int[1];
                result[0] = nums[left];
                return result;
            int mid = left+(right-left)/2;
            int[] a = mergeSort(nums,left,mid);
            int[] b = mergeSort(nums,mid+1,right);
            return merge(a,b);
        public int[] merge(int[] a, int[] b){
            int[] result = new int[a.length+b.length];
            for(int i=0,j=0,k=0;k<result.length;k++){
                if(i>=a.length) result[k] = b[j++];
                else if(j>=b.length) result[k] = a[i++];
                else if(a[i]<b[j]) result[k] = a[i++];
                else result[k] = b[j++];
            return result;

Log in to reply

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