1
1
<!DOCTYPE html>
2
2
< html lang ="en ">
3
-
4
- < head >
5
- < meta charset ="UTF-8 ">
6
- < meta name ="viewport " content ="width=device-width, initial-scale=1.0 ">
7
- < meta http-equiv ="X-UA-Compatible " content ="ie=edge ">
3
+ < head >
4
+ < meta charset ="UTF-8 " />
5
+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 " />
6
+ < meta http-equiv ="X-UA-Compatible " content ="ie=edge " />
8
7
< title > Document</ title >
9
- </ head >
8
+ </ head >
10
9
11
- < body >
10
+ < body >
12
11
< script >
13
- // Source : https://leetcode.com/problems/search-in-rotated-sorted-array/
14
- // Author : 悬笔e绝
15
- // Date : 2018-03-27
12
+ // Source : https://leetcode.com/problems/search-in-rotated-sorted-array/
13
+ // Author : 悬笔e绝
14
+ // Date : 2018-03-27
16
15
17
- /**
18
- * @param {number[] } nums
19
- * @param {number } target
20
- * @return {number }
21
- */
16
+ /**
17
+ * @param {number[] } nums
18
+ * @param {number } target
19
+ * @return {number }
20
+ */
22
21
23
- //不用管什么鬼“旋转排序数组”,for循环直接搞定
24
- var search = function ( nums , target ) {
25
- for ( var i = 0 , len = nums . length ; i < len ; i ++ )
26
- if ( nums [ i ] === target )
27
- return i ;
28
- return - 1 ;
29
- } ;
22
+ // 思路1:直接for循环遍历,时间复杂度O(n) 不满足要求
23
+ var search = function ( nums , target ) {
24
+ for ( var i = 0 , len = nums . length ; i < len ; i ++ )
25
+ if ( nums [ i ] === target ) return i ;
26
+ return - 1 ;
27
+ } ;
30
28
31
- //测试
32
- var nums = [ 4 , 5 , 6 , 7 , 0 , 1 , 2 ] ;
33
- console . log ( search ( nums , 1 ) ) ;
29
+ // 思路2:O(log n)就是要用二分查找
30
+ var search2 = function ( nums , target ) {
31
+ var len = nums . length ;
32
+ if ( len === 0 ) return - 1 ;
33
+ if ( len === 1 ) {
34
+ return nums [ 0 ] === target ? 0 : - 1 ;
35
+ }
36
+ var l = 0 ,
37
+ r = len - 1 ;
38
+ while ( l <= r ) {
39
+ var mid = Math . floor ( ( l + r ) / 2 ) ;
40
+ if ( target === nums [ mid ] ) {
41
+ return mid ;
42
+ }
43
+ if ( nums [ 0 ] <= nums [ mid ] ) {
44
+ //左边是有序的
45
+ if ( nums [ 0 ] <= target && target < nums [ mid ] ) {
46
+ r = mid - 1 ;
47
+ } else {
48
+ l = mid + 1 ;
49
+ }
50
+ } else {
51
+ //右边是有序的
52
+ if ( nums [ mid ] < target && target <= nums [ len - 1 ] ) {
53
+ l = mid + 1 ;
54
+ } else {
55
+ r = mid - 1 ;
56
+ }
57
+ }
58
+ }
59
+ return - 1 ;
60
+ } ;
34
61
62
+ //测试
63
+ // var nums = [4, 5, 6, 7, 0, 1, 2];
64
+ // var nums = [1, 3];
65
+ var nums = [ 3 , 1 ] ;
66
+ console . log ( search ( nums , 1 ) ) ;
67
+ console . log ( search2 ( nums , 1 ) ) ;
35
68
</ script >
36
- </ body >
37
-
38
- </ html >
69
+ </ body >
70
+ </ html >
0 commit comments