Java lambda sort w/o helper function


  • 0
    Z

    The idea of my solution is simple:

    1. put the string list into 2-dimension array;
    2. sort it with lambda expression;
    3. compare the distance of every pair of neighbors;
    4. compare the distance of the last time with the first. (23:59 and 00:00 have only 1 min difference not 1439)
      done.
    public class Solution {
        public int findMinDifference(List<String> timePoints) {
            int n = timePoints.size();
            if(n==0){
                return 0;
            }
            int[][] times = new int[n][2];
            for(int i =0;i<n;i++){
                times[i][0]=Integer.valueOf(timePoints.get(i).substring(0,2));
                times[i][1]=Integer.valueOf(timePoints.get(i).substring(3,5));
            }
            Arrays.sort(times, (a,b) -> a[0]==b[0]? a[1]-b[1] : a[0]-b[0]);
    //Here I set the min to the difference between the last time and the first one.*/
            int min = (times[n-1][0]-times[0][0])*60 + times[n-1][1]-times[0][1];
            if(min>720){
                min=1440-min;
            }
            for(int i = 1;i<n;i++){
                int gap = (times[i][0]-times[i-1][0])*60 + times[i][1]-times[i-1][1];
                if(gap<min){
                    min=gap;
                }
            }
            return min;
        }
    }
    

Log in to reply
 

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