My JAVA accepted code with Priority Queue (revised, easier to read)


  • 1
    M

    class MyNumber{

      int num;
      int indexInArray;
      int arrNum;
      public MyNumber(int num, int indexInArray, int arrNum) {
              this.num = num;
              this.indexInArray = indexInArray;
              this.arrNum = arrNum;
       }
    

    }

    '''
    public int[] smallestRange(int[][] nums) {

    list itemint[] res = new int[2];
    int minRangeSize = Integer.MAX_VALUE;
    if (nums == null) return res;
    PriorityQueue<MyNumber> queue = new PriorityQueue<MyNumber>
      (nums.length, new Comparator<MyNumber>(){
        public int compare(MyNumber myNum1, MyNumber myNum2) {
            return myNum1.num - myNum2.num;
        }
    });
    
    int maxValue = nums[0][0];
    for (int i = 0; i < nums.length; i++) {
         maxValue = Math.max(maxValue, nums[i][0]);
         MyNumber myNum = new MyNumber(nums[i][0], 0, i);
         queue.offer(myNum);
    }
    
    while (!queue.isEmpty()) {
         MyNumber myNum = queue.poll();
         if (maxValue - myNum.num < minRangeSize) {
             minRangeSize = maxValue - myNum.num;
             res[0] = myNum.num;
             res[1] = maxValue;
         }
    
        if (myNum.indexInArray == nums[myNum.arrNum].length - 1) {
            break;
        } else {
            int cur = nums[myNum.arrNum][myNum.indexInArray + 1];
            myNum = new MyNumber(cur, myNum.indexInArray + 1, myNum.arrNum);
            maxValue = Math.max(maxValue, cur);
            queue.offer(myNum);
       }
    }
    return res;
    

    }
    '''


Log in to reply
 

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