Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 62279be

Browse files
committed
solve 704.二分查找
1 parent 54ffa02 commit 62279be

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

‎zh/704.二分查找.java‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
* @lc app=leetcode.cn id=704 lang=java
3+
*
4+
* [704] 二分查找
5+
*
6+
* https://leetcode-cn.com/problems/binary-search/description/
7+
*
8+
* algorithms
9+
* Easy (53.71%)
10+
* Likes: 138
11+
* Dislikes: 0
12+
* Total Accepted: 52.3K
13+
* Total Submissions: 96.3K
14+
* Testcase Example: '[-1,0,3,5,9,12]\n9'
15+
*
16+
* 给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的
17+
* target,如果目标值存在返回下标,否则返回 -1。
18+
*
19+
*
20+
* 示例 1:
21+
*
22+
* 输入: nums = [-1,0,3,5,9,12], target = 9
23+
* 输出: 4
24+
* 解释: 9 出现在 nums 中并且下标为 4
25+
*
26+
*
27+
* 示例 2:
28+
*
29+
* 输入: nums = [-1,0,3,5,9,12], target = 2
30+
* 输出: -1
31+
* 解释: 2 不存在 nums 中因此返回 -1
32+
*
33+
*
34+
*
35+
*
36+
* 提示:
37+
*
38+
*
39+
* 你可以假设 nums 中的所有元素是不重复的。
40+
* n 将在 [1, 10000]之间。
41+
* nums 的每个元素都将在 [-9999, 9999]之间。
42+
*
43+
*
44+
*/
45+
46+
// @lc code=start
47+
class Solution {
48+
public int search(int[] nums, int target) {
49+
int left = 0;
50+
int right = nums.length - 1;
51+
while (left <= right) {
52+
int mid = left + (right - left) / 2;
53+
if (nums[mid] < target) {
54+
left = mid + 1;
55+
} else if (nums[mid] > target) {
56+
right = mid - 1;
57+
} else if (nums[mid] == target) {
58+
return mid;
59+
}
60+
}
61+
return -1;
62+
}
63+
}
64+
// @lc code=end
65+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /