Share my accepted java code


  • 3
    O

    My code is borrowed from many others ideas, and honestly it is not faster than others. I want to show one possible solution with a little bit more cleaner java code. Comments are welcome ;-)

    public class Solution {
        
            private class StringComparator implements Comparator<String> {
                public int compare(String x, String y) {
                    if (x.equals(y)) return 0;            
                    return -(x+y).compareTo(y+x);
                }
            }
                
            
            public String largestNumber(int[] num) {
                Comparator<String> comp = new StringComparator();
                PriorityQueue<String> queue = new PriorityQueue<String>(num.length, comp);
                
                for (int i = 0; i < num.length; i++) {
                    queue.add(String.valueOf(num[i]));
                }
                
                StringBuffer bf = new StringBuffer();
                while (!queue.isEmpty()) {
                    bf.append(queue.poll());
                }
                
                return bf.charAt(0) == '0' ? "0":bf.toString();
            }
        }

  • 1
    J

    How much time does it cost?mine is 229 ms.


  • 0
    O

    Mine was 242ms. Char-by-char comparator is faster (a little bit) than my current method, but it is more cleaner.


  • 0
    J

    This time, i improved my codes, but just 9 ms less -- 219 ms


  • 0
    X

    @jacktan1991 made small changes.
    Now it is 115ms. BTW,
    public String largestNumber(int[] num) {

       if (num == null || num.length == 0) return "";
        PriorityQueue<String> queue = new PriorityQueue<String>(num.length, new Comparator<String>(){
            public int compare(String s1, String s2) {
                return (s2 + s1).compareTo(s1 + s2);
            }
            
        });
        for (int i = 0; i < num.length; i++) {
            queue.add(String.valueOf(num[i]));
        }
        
        if(queue.peek().charAt(0) == '0')
            return "0";
        
        StringBuffer bf = new StringBuffer();
        while (!queue.isEmpty()) {
            bf.append(queue.poll());
        }
        
        return bf.toString();
    }

Log in to reply
 

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