提问人:qwe987 提问时间:10/26/2022 最后编辑:qwe987 更新时间:10/28/2022 访问量:276
如何确定数组中是否存在算术序列
How to find out if an arithmetic sequence exists in an array
问:
如果有一个数组包含按升序排列的随机整数,我如何判断这个数组是否包含具有公共微分 x 的算术序列(长度>3)?
示例:输入:array=[1,2,4,5,8,10,17,19,20,23,30,36,40,50] x=10 输出:True
示例说明:数组包含 [10,20,30,40,50],这是一个算术序列(长度=5),共有微分 10。
谢谢!
很抱歉,由于我还不知道,我没有尝试任何代码来解决这个问题。
看完答案后,我在python中尝试了一下。 这是我的代码:
df = [1,10,11,20,21,30,40]
i=0
common_differene=10
df_len=len(df)
for position_1 in range(df_len):
for position_2 in range(df_len):
if df[position_1] + common_differene == df[position_2]:
position_1=position_2
i=i+1
print(i)
但是,它返回 9 而不是 4。
有没有办法防止一个序列[10,20,30,40]的重复计数,并防止其他序列[1,11,21]的i累积?
答:
从 1 开始尝试:检查是否存在 11、21、31...(您可以立即停止)
从 2 开始尝试:检查是否存在 12、22、32...(您可以立即停止)
从 4 开始尝试:检查是否存在 14、24、34......(您可以立即停止)
...
从 10 开始尝试:检查是否存在 20、30、40...(宾果游戏!
您可以使用线性搜索,但对于大型数组,哈希映射会更好。如果找到长度为 3 >的序列后可以立即停止,则此过程需要线性时间。
越来越多地扫描列表,对于每个元素 v,检查元素 v + 10 是否存在并在它们之间绘制链接。此搜索可以作为修改后的合并操作在线性时间内完成。
例如,从 1 开始,搜索 11;你可以在 17 点停下来;从 2 开始,搜索 12;你可以在 17 点停下来;... ;从 8 开始,搜索 18;你可以停在 19 点......
现在你有一个图,其中的连接分量形成算术序列。您可以遍历数组以查找长序列(或最长序列),也可以以线性时间搜索。
在给定的示例中,唯一的链接是 10->-20->-30->-40->-50。
您可以通过使用 2 个循环来解决您的问题,一个循环遍历每个元素,另一个循环检查元素是否是 ,如果您找到一个循环,您可以在那里继续形成。
由于序列长度超过 2 个元素的附加规则,我在 FREE BASIC 中重新创建了您的问题:currentElement+x
DIM array(13) As Integer = {1, 2, 4, 5, 8, 10, 17, 19, 20, 23, 30, 36, 40, 50}
DIM x as Integer = 10
DIM arithmeticArrayMinLength as Integer = 3
DIM index as Integer = 0
FOR position As Integer = LBound(array) To UBound(array)
FOR position2 As Integer = LBound(array) To UBound(array)
IF (array(position) + x = array(position2)) THEN
position = position2
index = index + 1
END IF
NEXT
NEXT
IF (index <= arithmeticArrayMinLength) THEN
PRINT false
ELSE
PRINT true
END IF
希望对您有所帮助
编辑:
在查看了您的编辑后,我在 Python 中提出了一个解决方案,该解决方案返回所有算术序列,并保持列表的顺序:
def arithmeticSequence(A,n):
SubSequence=[]
ArithmeticSequences=[]
#Create array of pairs from array A
for index,item in enumerate(A[:-1]):
for index2,item2 in enumerate(A[index+1:]):
SubSequence.append([item,item2])
#finding arithmetic sequences
for index,pair in enumerate(SubSequence):
if (pair[1] - pair[0] == n):
found = [pair[0],pair[1]]
for index2,pair2 in enumerate(SubSequence[index+1:]):
if (pair2[0]==found[-1] and pair2[1]-pair2[0]==n):
found.append(pair2[1])
if (len(found)>2): ArithmeticSequences.append(found)
return ArithmeticSequences
df = [1,10,11,20,21,30,40]
common_differene=10
arseq=arithmeticSequence(df,common_differene)
print(arseq)
输出: [[1, 11, 21], [10, 20, 30, 40], [20, 30, 40]]
这就是你如何从中获取所有的算术序列,以便你对它们做任何你想做的事情。
现在,如果要删除已存在的算术序列的子序列,可以尝试通过以下方式运行它:df
def distinct(A):
DistinctArithmeticSequences = A
for index,item in enumerate(A):
for index2,item2 in enumerate([x for x in A if x != item]):
if (set(item2) <= set(item)):
DistinctArithmeticSequences.remove(item2)
return DistinctArithmeticSequences
darseq=distinct(arseq)
print(darseq)
输出: [[1, 11, 21], [10, 20, 30, 40]]
注意:不会撒谎,这很有趣!
评论
上一个:如何识别序列方程 Python
评论