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 d2c65be

Browse files
committed
solve 35.搜索插入位置
1 parent 94fe158 commit d2c65be

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

‎zh/35.搜索插入位置.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=35 lang=java
3+
*
4+
* [35] 搜索插入位置
5+
*
6+
* https://leetcode-cn.com/problems/search-insert-position/description/
7+
*
8+
* algorithms
9+
* Easy (45.58%)
10+
* Likes: 550
11+
* Dislikes: 0
12+
* Total Accepted: 179.4K
13+
* Total Submissions: 391.8K
14+
* Testcase Example: '[1,3,5,6]\n5'
15+
*
16+
* 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
17+
*
18+
* 你可以假设数组中无重复元素。
19+
*
20+
* 示例 1:
21+
*
22+
* 输入: [1,3,5,6], 5
23+
* 输出: 2
24+
*
25+
*
26+
* 示例 2:
27+
*
28+
* 输入: [1,3,5,6], 2
29+
* 输出: 1
30+
*
31+
*
32+
* 示例 3:
33+
*
34+
* 输入: [1,3,5,6], 7
35+
* 输出: 4
36+
*
37+
*
38+
* 示例 4:
39+
*
40+
* 输入: [1,3,5,6], 0
41+
* 输出: 0
42+
*
43+
*
44+
*/
45+
46+
// @lc code=start
47+
class Solution {
48+
public int searchInsert(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 left;
62+
}
63+
}
64+
// @lc code=end
65+

0 commit comments

Comments
(0)

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