-
Notifications
You must be signed in to change notification settings - Fork 181
/
41.hafl-search.js
47 lines (36 loc) · 1 KB
/
41.hafl-search.js
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// 704. 二分查找
/**
*
给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
示例 1:
输入: nums = [-1,0,3,5,9,12], target = 9
输出: 4
解释: 9 出现在 nums 中并且下标为 4
示例 2:
输入: nums = [-1,0,3,5,9,12], target = 2
输出: -1
解释: 2 不存在 nums 中因此返回 -1
提示:
你可以假设 nums 中的所有元素是不重复的。
n 将在 [1, 10000]之间。
nums 的每个元素都将在 [-9999, 9999]之间。
*/
// 这个解答很详细
const search = (nums, target) => {
let i = 0
let j = nums.length - 1
let midIndex = 0
while (i <= j) {
midIndex = Math.floor((i + j) / 2)
const midValue = nums[ midIndex ]
if (midValue === target) {
return midIndex
} else if (midValue < target) {
i = midIndex + 1
} else {
j = midIndex - 1
}
}
return -1
}
console.log(search([-1,0,3,5,9,12], 9))