Skip to content

Commit 4d17b37

Browse files
committed
Add solution 035.Search Insertion Location
1 parent 0c677f0 commit 4d17b37

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
## 搜索位置描述
2+
### 题目描述
3+
4+
5+
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
6+
7+
你可以假设数组中无重复元素。
8+
9+
示例 1:
10+
11+
输入: [1,3,5,6], 5
12+
输出: 2
13+
示例 2:
14+
15+
输入: [1,3,5,6], 2
16+
输出: 1
17+
示例 3:
18+
19+
输入: [1,3,5,6], 7
20+
输出: 4
21+
示例 4:
22+
23+
输入: [1,3,5,6], 0
24+
输出: 0
25+
26+
### 解法
27+
首先判断传入的数组为0,1这样的长度
28+
29+
因为是一个给定的排序数组,在循环时就可以判断是否存在的同时判断大小,有相同的则直接返回索引,
30+
不存在则判断大小,只要相较于当前索引的元素较小,则可以认为该目标数在数组中无对应元素,直接返回索引即可
31+
32+
除此之外还可用二分法做解
33+
34+
```java
35+
class Solution {
36+
public int searchInsert(int[] nums, int target) {
37+
if(nums.length == 0){
38+
return 0;
39+
}
40+
if(nums.length == 1){
41+
if(nums[0] < target){
42+
return 1;
43+
} else {
44+
return 0;
45+
}
46+
}
47+
for(int i = 0;i < nums.length;i++){
48+
if(nums[i] == target){
49+
return i;
50+
} else {
51+
int s = Math.min(nums[i],target);
52+
if(s == target){
53+
return i;
54+
}
55+
}
56+
}
57+
return nums.length;
58+
}
59+
}
60+
```
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public int searchInsert(int[] nums, int target) {
3+
if(nums.length == 0){
4+
return 0;
5+
}
6+
if(nums.length == 1){
7+
if(nums[0] < target){
8+
return 1;
9+
} else {
10+
return 0;
11+
}
12+
}
13+
for(int i = 0;i < nums.length;i++){
14+
if(nums[i] == target){
15+
return i;
16+
} else {
17+
int s = Math.min(nums[i],target);
18+
if(s == target){
19+
return i;
20+
}
21+
}
22+
}
23+
return nums.length;
24+
}
25+
}

0 commit comments

Comments
 (0)