Adjacent number algorithm grouper

前端 未结 13 1737
不思量自难忘°
不思量自难忘° 2021-02-15 06:55

By which I mean this:

Given the input set of numbers:

1,2,3,4,5 becomes \"1-5\".

1,2,3,5,7,9,10,11,12,14 becomes \"1-3, 5, 7, 9-12, 14\"

This is

13条回答
  •  一生所求
    2021-02-15 07:41

    Looks clear and straightforward to me. You can simplify a bit if you either assume the input array is sorted, or sort it yourself before further processing.

    The only tweak I'd suggest would be to reverse the subtraction:

    int difference = (current - lastNumber);

    ... simply because I find it easier to work with positive differences. But your code is a pleasure to read!

提交回复
热议问题