File tree Expand file tree Collapse file tree 2 files changed +85
-0
lines changed
solution/035.Search Insertion Location Expand file tree Collapse file tree 2 files changed +85
-0
lines changed Original file line number Diff line number Diff line change
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
+ ```
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments