Same DP solution, Why use Collections.sort is faster than Arrays.sort


  • 0
    J

    Collections sort 300 ms

    public class Solution {
        
        private class ArrayComparator implements Comparator<int[]> {
            @Override
            public int compare(int[] a, int[] b) {
                return a[0] - b[0];
            }
        }
        
        public int maxEnvelopes(int[][] envelopes) {
            if (envelopes == null || envelopes.length == 0) return 0;
            List<int[]> list = new ArrayList<>();
            for (int[] env : envelopes) list.add(env);
            Collections.sort(list, new ArrayComparator());
            int[] dp = new int[list.size()];
            int res = 0;
            Arrays.fill(dp, 1);
            for (int i = 0; i < list.size(); i++) {
                for (int j = 0; j < i; j++) {
                    if (list.get(i)[0] > list.get(j)[0] && list.get(i)[1] > list.get(j)[1]) {
                        dp[i] = Math.max(dp[i], 1 + dp[j]);
                    }
                }
                res = Math.max(res, dp[i]);
            }
            return res;
        }
    }
    

    Use Arrays.sort need 600ms

    public class Solution {
        
        private class ArrayComparator implements Comparator<int[]> {
            @Override
            public int compare(int[] a, int[] b) {
                return a[0] - b[0];
            }
        }
        
        public int maxEnvelopes(int[][] envelopes) {
            if (envelopes == null || envelopes.length == 0) return 0;
            int n = envelopes.length, res = 0;
            Arrays.sort(envelopes, new ArrayComparator());
            int[] dp = new int[n];
            Arrays.fill(dp, 1);
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < i; j++) {
                    if (envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1]) {
                        dp[i] = Math.max(dp[i], 1 + dp[j]);
                    }
                }
                res = Math.max(res, dp[i]);
            }
            return res;
        }
    }

Log in to reply
 

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