检查数组中的整数是连续的还是顺序的 [英] Check whether integers in array are consecutive or in sequence

查看:50
本文介绍了检查数组中的整数是连续的还是顺序的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有最好的方法来检查数组中的元素是否连续?

Is there any best method to check if elements in array are in consecutive order?

例如:

[1,2,3,4,5] // returns true 
[1,2,4,3,5] // returns false

目前,我实现的是对元素进行求和,如果diff为1,那么我说它是连续的.

Currently what I implement is to take difference of elements and if the diff is 1 then I say it is in consecutive order.

我正在寻找任何改进的方法.我想为Array添加扩展名,但不确定如何实现.

I'm looking for any improved approach. I think of adding extension to Array but not sure how to implement this.

推荐答案

给出数组

let list = [1,2,3,4,5]

您可以使用一些函数式编程魔术

you can use some Functional Programming magic

let consecutives = list.map { $0 - 1 }.dropFirst() == list.dropLast()

这篇关于检查数组中的整数是连续的还是顺序的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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