-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinarySearchTest
60 lines (52 loc) · 1.4 KB
/
BinarySearchTest
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
48
49
50
51
52
53
54
55
56
57
58
59
60
package com.aseit;
/**
* Created with IntelliJ IDEA.
* User: @ziyu [email protected]
* Date: 2019-03-27
* Time: 19:56
* Description:
* 在一个排序数组中找一个数,返回该数出现的任意位置,如果不存在,返回 -1。
* 样例
* 样例 1:
* <p>
* 输入:nums = [1,2,2,4,5,5], target = 2
* 输出:1 或者 2
* 样例 2:
* <p>
* 输入:nums = [1,2,2,4,5,5], target = 6
* 输出:-1
* 挑战
* O(logn) 的时间
*/
import java.util.Scanner;
/**
* 解析:二分查找,首先是数组已经是排序好的。
*/
public class BinarySearchTest {
public static void main(String args[]) {
int[] arr = new int[6];
Scanner sc = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}
int key = sc.nextInt();
int a = search(arr, key);
System.out.println(a);
}
public static int search(int[] arr, int key) {
int start = 0;
int end = arr.length - 1;
while (start <= end) {
int middle = start + (end-start) / 2;
//目标元素比中值小的时候则最后一个元素左移
if (key < middle) {
end = middle - 1;
} else if (key > middle) {
start = middle + 1;
} else {
return middle;
}
}
return -1;
}
}