检查数组中的 3 个值是否连续?
我有一个数组,例如包含值 123456,它显然包含超过 3 个连续值。
我想要一个方法,如果数组中至少包含 3 个连续值,该方法将返回 true,提前致谢。
例如:
972834 - 返回 true (234)
192645 - 返回 true (456)
等等..
更新! :
我在java中有一个数组,它接受6个整数。 例如nextTurn[],它包含8 4 2 5 6 5 目前它对数组进行排序 - 2 4 5 5 6 8
如果整个数组中有 3 个连续的数字,我如何让它返回 true?
即它会找到 4 5 6
我还希望它返回数组中整数的位置, 所以对于原始数组 8 4 2 5 6 5
它将返回 2 4 5 或 2 5 6
感谢你们所有的帮助,非常感谢
I have an array, which for example contains the values 123456, which obviously contains more than 3 consecutive values.
I want a method that will return true if the array contains at least 3 consecutive values in it, thanks in advance.
for example:
972834 - return true (234)
192645 - return true (456)
etc. etc..
update! :
i have an array in java, it takes in 6 integers.
for example nextTurn[], and it contains 8 4 2 5 6 5
at the moment it sorts the array - 2 4 5 5 6 8
how would i get it to return true if there are 3 consecutive numbers throughout the array?
ie so it will find 4 5 6
i would also like it to return the position of the integer in the array,
so for the original array 8 4 2 5 6 5
it will return, 2 4 5
or 2 5 6
thanks for all your help guys, appreciated
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最直接的解决方案是简单地循环遍历项目,并检查接下来的两项:
另一个解决方案是循环遍历项目并计算连续的项目:
The most straight forward solution would be to simply loop through the items, and check against the next two items:
Another solution is to loop through the items and count consecutive items:
我猜应该给作业贴上标签。
在伪代码中,您将需要一些与
编辑相关的内容:这是假设您有一个整数数组。如果它是一个字符串,则必须使用类似于 charAt(position) 的内容,然后通过减去“0”或使用 parseInteger 函数将 char 转换为十进制数
更新误导部分 然后循环遍历字符串数组中的每个项目,
为此,我将创建一个与字符串长度相同的数组,为了简单起见,
同时在数字所在的位置递增 arr
(假设是一个 char 数组,单个数字)
for( int i = 0; i < array.length; i++ )
arr[数组[i] - '0']++;
然后通过 arr 检查三个连续的数字
Should be tagged homework I'm assuming.
In pseudo code you are going to want something along the lines of
edit: This is assuming you have an array of ints. If it is a string, you are going to have to use something along the lines of charAt(position) and then convert the char to a decimal number, by subtracting '0' or using a parseInteger function
Update on the misleading part
To do this, I would create an array the same length of the string, for simplicities sake
then loop through every item in the string array, while incrementing arr at the position the number falls at
(assuming a char array, single digit numbers)
for( int i = 0; i < array.length; i++ )
arr[array[i] - '0']++;
then go through arr checking for three consecutive numbers
聚会迟到了,但这里有一个解决方案。
这是一个蛮力解决方案,所以不是最优的。
Late to the party, but here's a solution.
It's a brute force solution, so not the most optimal.