File tree Expand file tree Collapse file tree 2 files changed +88
-0
lines changed Expand file tree Collapse file tree 2 files changed +88
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 题目说明
2
+
3
+ 在一个存有循环排序的数组中找某个数的序号,直接使用暴力法遍历,结果却可以通过,估计是设计有误,暴力法实现代码如下:
4
+
5
+ ``` python
6
+ class Solution (object ):
7
+ def search (self , nums , target ):
8
+ """
9
+ :type nums: List[int]
10
+ :type target: int
11
+ :rtype: int
12
+ """
13
+ for i in range (len (nums)):
14
+ if nums[i] == target:
15
+ return i
16
+ return - 1
17
+ ```
18
+
19
+ 如果是这样实现就没多大意思,下面用其他方法解决。
20
+
21
+ 用一种改进的二分搜索法,取中间值,比较大小,判断左、右有序,进行循环查找,实现代码如下:
22
+
23
+ ``` python
24
+ class Solution (object ):
25
+ def search (self , nums , target ):
26
+ """
27
+ :type nums: List[int]
28
+ :type target: int
29
+ :rtype: int
30
+ """
31
+ if not nums:
32
+ return - 1
33
+
34
+ low, high = 0 , len (nums) - 1
35
+ while low <= high:
36
+ mid = (low + high) / 2
37
+ if target == nums[mid]:
38
+ return mid
39
+ if nums[low] <= nums[mid]:
40
+ if nums[low] <= target and nums[mid] >= target:
41
+ high = mid - 1
42
+ else :
43
+ low = mid + 1
44
+ else :
45
+ if nums[mid] <= target and target <= nums[high]:
46
+ low = mid + 1
47
+ else :
48
+ high = mid - 1
49
+ return - 1
50
+ ```
51
+
Original file line number Diff line number Diff line change
1
+ #-*- coding:utf-8 -*-
2
+ '''
3
+ Created on 2017年5月22日
4
+
5
+ @author: huangjiaxin
6
+ '''
7
+ class Solution (object ):
8
+ def search (self , nums , target ):
9
+ """
10
+ :type nums: List[int]
11
+ :type target: int
12
+ :rtype: int
13
+ """
14
+ if not nums :
15
+ return - 1
16
+
17
+ low , high = 0 , len (nums ) - 1
18
+ while low <= high :
19
+ mid = (low + high ) / 2
20
+ if target == nums [mid ]:
21
+ return mid
22
+ if nums [low<
8000
/span>] <= nums [mid ]:
23
+ if nums [low ] <= target and nums [mid ] >= target :
24
+ high = mid - 1
25
+ else :
26
+ low = mid + 1
27
+ else :
28
+ if nums [mid ] <= target and target <= nums [high ]:
29
+ low = mid + 1
30
+ else :
31
+ high = mid - 1
32
+ return - 1
33
+
34
+
35
+ if __name__ == '__main__' :
36
+ S = [1 ,3 ,5 ]
37
+ print Solution ().search (S , 3 )
You can’t perform that action at this time.
0 commit comments