Concise Java - Priority Queue


  • 0

    We can use a simple priority queue to sort the time points in 1 pass.
    Priority queue makes clear and concise code.

        public int findMinDifference(List<String> timePoints) {
            PriorityQueue<Integer> pq = new PriorityQueue<>(); 
            for (int i = 0; i < timePoints.size(); i++) {
                int hrs = Integer.parseInt(timePoints.get(i).substring(0, 2)); 
                int mins = Integer.parseInt(timePoints.get(i).substring(3)); 
                pq.offer(60 * hrs + mins);
                pq.offer(60 * (hrs + 24) + mins);
            }
            int min = Integer.MAX_VALUE, cur = pq.poll(), next = 0; 
            while(!pq.isEmpty()) {
                next = pq.poll();
                min = Math.min(min, Math.abs(cur - next));
                cur = next; 
            }
            return min; 
        }

Log in to reply
 

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