How can I sort numbers lexicographically?

前端 未结 14 931
半阙折子戏
半阙折子戏 2020-12-09 04:56

Here is the scenario.

I am given an array \'A\' of integers. The size of the array is not fixed. The function that I am supposed to write may be called once with an

14条回答
  •  一向
    一向 (楼主)
    2020-12-09 05:56

    Since you mentioned Java is the actual language in question:

    You don't need to convert to and from strings. Instead, define your own comparator and use that in the sort.

    Specifically:

    Comparator lexCompare = new Comparator(){
       int compareTo( Integer x, Integer y ) {
          return x.toString().compareTo( y.toString() );
       }
    };
    

    Then you can sort the array like this:

    int[] array = /* whatever */;
    Arrays.sort( array, lexCompare );
    

    (Note: The int/Integer mismatch works automatically through auto-boxing)

提交回复
热议问题