Skip to content

Commit dcb2adb

Browse files
committed
35. Search Insert Position
1 parent 6ac504d commit dcb2adb

File tree

3 files changed

+76
-0
lines changed

3 files changed

+76
-0
lines changed

src/leetcode/_35_/Main.java

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package leetcode._35_;
2+
3+
/**
4+
* Created by zhangbo54 on 2019-03-04.
5+
*/
6+
public class Main {
7+
public static void main(String[] args) {
8+
Solution solution = new Solution();
9+
System.out.println(solution.searchInsert(new int[]{1, 3, 5, 6}, 5));
10+
System.out.println(solution.searchInsert(new int[]{1, 3, 5, 6}, 2));
11+
System.out.println(solution.searchInsert(new int[]{1, 3, 5, 6}, 7));
12+
System.out.println(solution.searchInsert(new int[]{1, 3, 5, 6}, 0));
13+
}
14+
}
15+

src/leetcode/_35_/Solution.java

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package leetcode._35_;
2+
3+
import java.util.Arrays;
4+
5+
class Solution {
6+
public int searchInsert(int[] nums, int target) {
7+
int index = Arrays.binarySearch(nums, target);
8+
return index < 0 ? -index - 1 : index;
9+
}
10+
}

src/leetcode/_35_/solution.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
### [35\. Search Insert PositionCopy for MarkdownCopy for MarkdownCopy for MarkdownCopy for Markdown](https://leetcode.com/problems/search-insert-position/)
2+
3+
Difficulty: **Easy**
4+
5+
6+
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
7+
8+
You may assume no duplicates in the array.
9+
10+
**Example 1:**
11+
12+
```
13+
Input: [1,3,5,6], 5
14+
Output: 2
15+
```
16+
17+
**Example 2:**
18+
19+
```
20+
Input: [1,3,5,6], 2
21+
Output: 1
22+
```
23+
24+
**Example 3:**
25+
26+
```
27+
Input: [1,3,5,6], 7
28+
Output: 4
29+
```
30+
31+
**Example 4:**
32+
33+
```
34+
Input: [1,3,5,6], 0
35+
Output: 0
36+
```
37+
38+
39+
#### Solution
40+
41+
Language: **Java**
42+
43+
```java
44+
class Solution {
45+
   public int searchInsert(int[] nums, int target) {
46+
       int index = Arrays.binarySearch(nums, target);
47+
       return index < 0 ? -index - 1 : index;
48+
  }
49+
}
50+
```
51+
![](https://ws3.sinaimg.cn/large/006tKfTcgy1g13koxtxs3j31160ra0wl.jpg)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy