How would you display an array of integers as a set of ranges? (algorithm)

后端 未结 16 2972
我在风中等你
我在风中等你 2021-02-15 18:04

Given an array of integers, what is the simplest way to iterate over it and figure out all the ranges it covers? for example, for an array such as:

$numbers = ar         


        
16条回答
  •  自闭症患者
    2021-02-15 18:16

    Assuming the list is ordered you could start at the end and keep subtracting the next one down. While the difference is 1, you're in a range. When it's not, you start a new range.

    i.e

    16-15 = 1

    15-14 = 1

    14-12 = 2, the range is 16-14 - start a new range.

提交回复
热议问题