你会怎么显示整数数组为一组范围? (算法) [英] How would you display an array of integers as a set of ranges? (algorithm)
问题描述
由于整数数组,什么是迭代,并计算出所有覆盖范围最简单的方法是什么?例如,对于一个阵列如:
$数=阵列(1,3,4,5,6,8,11,12,14,15,16);
的范围是:
1,3-6,8,11-12,14-16
如果该数组按升序排序,那么问题很容易。定义范围
结构或类,它有一个开始和结束。然后经过阵列。如果当前元素比previous,更新 Range.end
一多,否则,创建一个新的范围,这个元素作为 Range.begin
。存储范围为动态阵列或链表。或只是打印出来,当您去。
如果该阵列可以不进行排序,然后先排序。
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 = array(1,3,4,5,6,8,11,12,14,15,16);
The ranges would be:
1,3-6,8,11-12,14-16
If the array is sorted in ascending order, then the problem is easy. Define a Range
structure or class, which has a beginning and an end. Then go through the array. If the current element is one more than the previous, update Range.end
, otherwise create a new range with this element as Range.begin
. Store the ranges to a dynamic array or a linked list. Or just print them out as you go.
If the array may not be sorted, then sort it first.
这篇关于你会怎么显示整数数组为一组范围? (算法)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!