Java solution,merge list


  • 0
    C
    public class Solution {
        public int kthSmallest(int[][] matrix, int k) {
            return merge(matrix,0,matrix.length-1)[k-1];
            
        }
        
        private int[] merge(int[][] matrix,int lo,int hi){
            if(lo > hi){
                return null;
            }
            if(lo == hi){
                return matrix[lo];
            }
            if(hi - lo == 1){
                return mergeTwo(matrix[lo],matrix[hi]);
            }
            int mid = lo + (hi-lo)/2;
            return mergeTwo(merge(matrix,lo,mid),merge(matrix,mid+1,hi));
        }
        
        private int[] mergeTwo(int[] first,int[] second){
            if(first == null || first.length == 0){
                return second;
            }
            if(second == null || second.length == 0){
                return first;
            }
            int i=0,j=0,index=0;
            int[] result = new int[first.length + second.length];
            while(i<first.length || j<second.length){
                if(i<first.length &&(j>=second.length || first[i] <= second[j])){
                    result[index++] = first[i++];
                }
                if(j<second.length && (i>=first.length || second[j] < first[i])){
                    result[index++] = second[j++];
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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