您如何将整数数组显示为一组范围?(算法) [英] How would you display an array of integers as a set of ranges? (algorithm)

查看:18
本文介绍了您如何将整数数组显示为一组范围?(算法)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个整数数组,迭代它并找出它所涵盖的所有范围的最简单方法是什么?例如,对于一个数组,例如:

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);

范围是:

 1,3-6,8,11-12,14-16

推荐答案

如果数组按升序排序,那么问题就简单了.定义一个 Range 结构或类,它有一个开始和一个结束.然后遍历数组.如果当前元素比前一个元素多一个,则更新 Range.end,否则以该元素创建一个新的范围为 Range.begin.将范围存储到动态数组或链表中.或者直接打印出来.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆