Leetcode 题解 - 二分查找.md 8.1 KB
Newer Older
C
CyC2018 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<!-- GFM-TOC -->
* [原理](#原理)
    * [1. 正常实现](#1-正常实现)
    * [2. 时间复杂度](#2-时间复杂度)
    * [3. m 计算](#3-m-计算)
    * [4. 返回值](#4-返回值)
    * [5. 变种](#5-变种)
* [例题](#例题)
    * [1. 求开方](#1-求开方)
    * [2. 大于给定元素的最小元素](#2-大于给定元素的最小元素)
    * [3. 有序数组的 Single Element](#3-有序数组的-single-element)
    * [4. 第一个错误的版本](#4-第一个错误的版本)
    * [5. 旋转数组的最小数字](#5-旋转数组的最小数字)
    * [6. 查找区间](#6-查找区间)
<!-- GFM-TOC -->


# 原理

## 1. 正常实现
C
CyC2018 已提交
21 22

```java
C
CyC2018 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35
public int binarySearch(int[] nums, int key) {
    int l = 0, h = nums.length - 1;
    while (l <= h) {
        int m = l + (h - l) / 2;
        if (nums[m] == key) {
            return m;
        } else if (nums[m] > key) {
            h = m - 1;
        } else {
            l = m + 1;
        }
    }
    return -1;
C
CyC2018 已提交
36 37 38
}
```

C
CyC2018 已提交
39
## 2. 时间复杂度
C
CyC2018 已提交
40

C
CyC2018 已提交
41
二分查找也称为折半查找,每次都能将查找区间减半,这种折半特性的算法时间复杂度为 O(logN)。
C
CyC2018 已提交
42

C
CyC2018 已提交
43
## 3. m 计算
C
CyC2018 已提交
44

C
CyC2018 已提交
45
有两种计算中值 m 的方式:
C
CyC2018 已提交
46

C
CyC2018 已提交
47 48
- m = (l + h) / 2
- m = l + (h - l) / 2
C
CyC2018 已提交
49

C
CyC2018 已提交
50
l + h 可能出现加法溢出,最好使用第二种方式。
C
CyC2018 已提交
51

C
CyC2018 已提交
52
## 4. 返回值
C
CyC2018 已提交
53

C
CyC2018 已提交
54
循环退出时如果仍然没有查找到 key,那么表示查找失败。可以有两种返回值:
C
CyC2018 已提交
55

C
CyC2018 已提交
56 57
- -1:以一个错误码表示没有查找到 key
- l:将 key 插入到 nums 中的正确位置
C
CyC2018 已提交
58

C
CyC2018 已提交
59
## 5. 变种
C
CyC2018 已提交
60

C
CyC2018 已提交
61
二分查找可以有很多变种,变种实现要注意边界值的判断。例如在一个有重复元素的数组中查找 key 的最左位置的实现如下:
C
CyC2018 已提交
62 63

```java
C
CyC2018 已提交
64 65 66 67 68 69 70 71 72 73 74
public int binarySearch(int[] nums, int key) {
    int l = 0, h = nums.length - 1;
    while (l < h) {
        int m = l + (h - l) / 2;
        if (nums[m] >= key) {
            h = m;
        } else {
            l = m + 1;
        }
    }
    return l;
C
CyC2018 已提交
75 76 77 78 79
}
```

该实现和正常实现有以下不同:

C
CyC2018 已提交
80 81 82
- 循环条件为 l < h
- h 的赋值表达式为 h = m
- 最后返回 l 而不是 -1
C
CyC2018 已提交
83

C
CyC2018 已提交
84
在 nums[m] >= key 的情况下,可以推导出最左 key 位于 [l, m] 区间中,这是一个闭区间。h 的赋值表达式为 h = m,因为 m 位置也可能是解。
C
CyC2018 已提交
85

C
CyC2018 已提交
86
在 h 的赋值表达式为 h = mid 的情况下,如果循环条件为 l <= h,那么会出现循环无法退出的情况,因此循环条件只能是 l < h。以下演示了循环条件为 l <= h 时循环无法退出的情况:
C
CyC2018 已提交
87 88

```text
C
CyC2018 已提交
89 90 91 92 93 94
nums = {0, 1, 2}, key = 1
l   m   h
0   1   2  nums[m] >= key
0   0   1  nums[m] < key
1   1   1  nums[m] >= key
1   1   1  nums[m] >= key
C
CyC2018 已提交
95 96 97
...
```

C
CyC2018 已提交
98
当循环体退出时,不表示没有查找到 key,因此最后返回的结果不应该为 -1。为了验证有没有查找到,需要在调用端判断一下返回位置上的值和 key 是否相等。
C
CyC2018 已提交
99

C
CyC2018 已提交
100
# 例题
C
CyC2018 已提交
101

C
CyC2018 已提交
102
## 1. 求开方
C
CyC2018 已提交
103

C
CyC2018 已提交
104
[69. Sqrt(x) (Easy)](https://leetcode.com/problems/sqrtx/description/)
C
CyC2018 已提交
105 106

```html
C
CyC2018 已提交
107 108
Input: 4
Output: 2
C
CyC2018 已提交
109

C
CyC2018 已提交
110 111 112
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since we want to return an integer, the decimal part will be truncated.
C
CyC2018 已提交
113 114
```

C
CyC2018 已提交
115
一个数 x 的开方 sqrt 一定在 0 \~ x 之间,并且满足 sqrt == x / sqrt。可以利用二分查找在 0 \~ x 之间查找 sqrt。
C
CyC2018 已提交
116

C
CyC2018 已提交
117
对于 x = 8,它的开方是 2.82842...,最后应该返回 2 而不是 3。在循环条件为 l <= h 并且循环退出时,h 总是比 l 小 1,也就是说 h = 2,l = 3,因此最后的返回值应该为 h 而不是 l。
C
CyC2018 已提交
118 119

```java
C
CyC2018 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
public int mySqrt(int x) {
    if (x <= 1) {
        return x;
    }
    int l = 1, h = x;
    while (l <= h) {
        int mid = l + (h - l) / 2;
        int sqrt = x / mid;
        if (sqrt == mid) {
            return mid;
        } else if (mid > sqrt) {
            h = mid - 1;
        } else {
            l = mid + 1;
        }
    }
    return h;
C
CyC2018 已提交
137 138 139
}
```

C
CyC2018 已提交
140
## 2. 大于给定元素的最小元素
C
CyC2018 已提交
141

C
CyC2018 已提交
142
[744. Find Smallest Letter Greater Than Target (Easy)](https://leetcode.com/problems/find-smallest-letter-greater-than-target/description/)
C
CyC2018 已提交
143 144 145

```html
Input:
C
CyC2018 已提交
146 147 148
letters = ["c", "f", "j"]
target = "d"
Output: "f"
C
CyC2018 已提交
149 150

Input:
C
CyC2018 已提交
151 152 153
letters = ["c", "f", "j"]
target = "k"
Output: "c"
C
CyC2018 已提交
154 155
```

C
CyC2018 已提交
156
题目描述:给定一个有序的字符数组 letters 和一个字符 target,要求找出 letters 中大于 target 的最小字符,如果找不到就返回第 1 个字符。
C
CyC2018 已提交
157 158

```java
C
CyC2018 已提交
159 160 161 162 163 164 165 166 167 168 169 170
public char nextGreatestLetter(char[] letters, char target) {
    int n = letters.length;
    int l = 0, h = n - 1;
    while (l <= h) {
        int m = l + (h - l) / 2;
        if (letters[m] <= target) {
            l = m + 1;
        } else {
            h = m - 1;
        }
    }
    return l < n ? letters[l] : letters[0];
C
CyC2018 已提交
171 172 173
}
```

C
CyC2018 已提交
174
## 3. 有序数组的 Single Element
C
CyC2018 已提交
175

C
CyC2018 已提交
176
[540. Single Element in a Sorted Array (Medium)](https://leetcode.com/problems/single-element-in-a-sorted-array/description/)
C
CyC2018 已提交
177 178

```html
C
CyC2018 已提交
179 180
Input: [1, 1, 2, 3, 3, 4, 4, 8, 8]
Output: 2
C
CyC2018 已提交
181 182
```

C
CyC2018 已提交
183
题目描述:一个有序数组只有一个数不出现两次,找出这个数。要求以 O(logN) 时间复杂度进行求解。
C
CyC2018 已提交
184

C
CyC2018 已提交
185
令 index 为 Single Element 在数组中的位置。如果 m 为偶数,并且 m + 1 < index那么 nums[m] == nums[m + 1];m + 1 >= index,那么 nums[m] != nums[m + 1]。
C
CyC2018 已提交
186

C
CyC2018 已提交
187
从上面的规律可以知道,如果 nums[m] == nums[m + 1],那么 index 所在的数组位置为 [m + 2, h],此时令 l = m + 2;如果 nums[m] != nums[m + 1],那么 index 所在的数组位置为 [l, m],此时令 h = m。
C
CyC2018 已提交
188

C
CyC2018 已提交
189
因为 h 的赋值表达式为 h = m,那么循环条件也就只能使用 l < h 这种形式。
C
CyC2018 已提交
190 191

```java
C
CyC2018 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205
public int singleNonDuplicate(int[] nums) {
    int l = 0, h = nums.length - 1;
    while (l < h) {
        int m = l + (h - l) / 2;
        if (m % 2 == 1) {
            m--;   // 保证 l/h/m 都在偶数位,使得查找区间大小一直都是奇数
        }
        if (nums[m] == nums[m + 1]) {
            l = m + 2;
        } else {
            h = m;
        }
    }
    return nums[l];
C
CyC2018 已提交
206 207 208
}
```

C
CyC2018 已提交
209
## 4. 第一个错误的版本
C
CyC2018 已提交
210

C
CyC2018 已提交
211
[278. First Bad Version (Easy)](https://leetcode.com/problems/first-bad-version/description/)
C
CyC2018 已提交
212

C
CyC2018 已提交
213
题目描述:给定一个元素 n 代表有 [1, 2, ..., n] 版本,可以调用 isBadVersion(int x) 知道某个版本是否错误,要求找到第一个错误的版本。
C
CyC2018 已提交
214

C
CyC2018 已提交
215
如果第 m 个版本出错,则表示第一个错误的版本在 [l, m] 之间,令 h = m;否则第一个错误的版本在 [m + 1, h] 之间,令 l = m + 1。
C
CyC2018 已提交
216

C
CyC2018 已提交
217
因为 h 的赋值表达式为 h = m,因此循环条件为 l < h。
C
CyC2018 已提交
218 219

```java
C
CyC2018 已提交
220 221 222 223 224 225 226 227 228 229 230
public int firstBadVersion(int n) {
    int l = 1, h = n;
    while (l < h) {
        int mid = l + (h - l) / 2;
        if (isBadVersion(mid)) {
            h = mid;
        } else {
            l = mid + 1;
        }
    }
    return l;
C
CyC2018 已提交
231 232 233
}
```

C
CyC2018 已提交
234
## 5. 旋转数组的最小数字
C
CyC2018 已提交
235

C
CyC2018 已提交
236
[153. Find Minimum in Rotated Sorted Array (Medium)](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/description/)
C
CyC2018 已提交
237 238

```html
C
CyC2018 已提交
239 240
Input: [3,4,5,1,2],
Output: 1
C
CyC2018 已提交
241 242 243
```

```java
C
CyC2018 已提交
244 245 246 247 248 249 250 251 252 253 254
public int findMin(int[] nums) {
    int l = 0, h = nums.length - 1;
    while (l < h) {
        int m = l + (h - l) / 2;
        if (nums[m] <= nums[h]) {
            h = m;
        } else {
            l = m + 1;
        }
    }
    return nums[l];
C
CyC2018 已提交
255 256 257
}
```

C
CyC2018 已提交
258
## 6. 查找区间
C
CyC2018 已提交
259

C
CyC2018 已提交
260
[34. Search for a Range (Medium)](https://leetcode.com/problems/search-for-a-range/description/)
C
CyC2018 已提交
261 262

```html
C
CyC2018 已提交
263 264
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
C
CyC2018 已提交
265

C
CyC2018 已提交
266 267
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]
C
CyC2018 已提交
268 269 270
```

```java
C
CyC2018 已提交
271 272 273 274 275 276 277 278
public int[] searchRange(int[] nums, int target) {
    int first = binarySearch(nums, target);
    int last = binarySearch(nums, target + 1) - 1;
    if (first == nums.length || nums[first] != target) {
        return new int[]{-1, -1};
    } else {
        return new int[]{first, Math.max(first, last)};
    }
C
CyC2018 已提交
279 280
}

C
CyC2018 已提交
281 282 283 284 285 286 287 288 289 290 291
private int binarySearch(int[] nums, int target) {
    int l = 0, h = nums.length; // 注意 h 的初始值
    while (l < h) {
        int m = l + (h - l) / 2;
        if (nums[m] >= target) {
            h = m;
        } else {
            l = m + 1;
        }
    }
    return l;
C
CyC2018 已提交
292 293 294
}
```

C
CyC2018 已提交
295 296 297 298




C
CyC2018 已提交
299
</br><div align="center"> <img src="https://cyc-1256109796.cos.ap-guangzhou.myqcloud.com/%E5%85%AC%E4%BC%97%E5%8F%B7%20%E6%B5%B7%E6%8A%A5.png" width="500px"> </div></br>