方法一:使用正则表达式
输入示例1
6
1 2 3 4 5 6
3
输出示例1:
2 2
输入2:
7
1 2 3 3 3 5 6 7
3
输出2:
2 4
输入3:
6
1 2 3 4 5 6
9
输出3:
-1 -1
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21import re import sys def get_index(): """ 输入三个数据:首先是数组的长度;然后就是对应长度的数组,该数组从小到大排列;然后就是要寻找的数字 输入:如果找不到对应数字,那么输出: -1 -1 ,如果找到对应的数字,那么输出对应数字的下标 :return:如果要寻找的数字在数组里面,则输出该数字的起始下标和结束下标,如果该数字不在数组里面,则输入 -1 -1 """ length = sys.stdin.readline().strip() arr = sys.stdin.readline().strip().split() char = sys.stdin.readline().strip() string = "".join(arr) regex = re.compile(char+"+") match = regex.search(string) if match: a, b = match.span() print(a,b-1) else: print(-1, -1) get_index()
方法二:循环遍历
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26import sys def search(): lenth = int(sys.stdin.readline().strip()) arr = [int(x) for x in sys.stdin.readline().strip().split()] num = int(sys.stdin.readline().strip()) index1 = -1 count = 0 i = 0 while i <lenth: if arr[i] == num: j = i+1 while j < lenth : if arr[j]==num: count +=1 j+=1 index1 = i break i += 1 if index1 == -1: print(-1, -1) else: print(index1,index1+count ) search()
最后
以上就是幸福白羊最近收集整理的关于在有序数组中,寻找指定连续数字的起始下标和结束下标的全部内容,更多相关在有序数组中,寻找指定连续数字内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复