Skip to content

Commit 78d650e

Browse files
李晶李晶
李晶
authored and
李晶
committed
提交 33 旋转排序数组 二分法查找
1 parent eb88ba1 commit 78d650e

File tree

1 file changed

+60
-28
lines changed

1 file changed

+60
-28
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,38 +1,70 @@
11
<!DOCTYPE html>
22
<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" />
87
<title>Document</title>
9-
</head>
8+
</head>
109

11-
<body>
10+
<body>
1211
<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
1615

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+
*/
2221

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+
};
3028

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+
};
3461

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));
3568
</script>
36-
</body>
37-
38-
</html>
69+
</body>
70+
</html>

0 commit comments

Comments
 (0)