-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathq035_SearchInsertPosition.java
More file actions
70 lines (54 loc) · 2.09 KB
/
q035_SearchInsertPosition.java
File metadata and controls
70 lines (54 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package leetcode_algorithm;
/**
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.
You may assume no duplicates in the array.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
*/
public class q035_SearchInsertPosition {
public static void main(String[] args) {
System.out.println(new q035_SearchInsertPosition().searchInsert(new int[]{1, 3, 5, 6}, 5));
System.out.println(new q035_SearchInsertPosition().searchInsert(new int[]{1, 3, 5, 6}, 2));
System.out.println(new q035_SearchInsertPosition().searchInsert(new int[]{1, 3, 5, 6}, 7));
System.out.println(new q035_SearchInsertPosition().searchInsert(new int[]{1, 3, 5, 6}, 0));
System.out.println(new q035_SearchInsertPosition().searchInsert1(new int[]{1, 3, 5, 6}, 5));
System.out.println(new q035_SearchInsertPosition().searchInsert1(new int[]{1, 3, 5, 6}, 2));
System.out.println(new q035_SearchInsertPosition().searchInsert1(new int[]{1, 3, 5, 6}, 7));
System.out.println(new q035_SearchInsertPosition().searchInsert1(new int[]{1, 3, 5, 6}, 0));
}
/**
* 解法1 (个人解法)
* @param nums
* @param target
* @return
*/
public int searchInsert(int[] nums, int target) {
int position = 0;
for(int i = 0;i < nums.length;i++) {
position = i;
if(nums[i] == target) return i;
if(nums[i] > target) break;
}
if(nums[position] < target) return position+1;
return position;
}
/**
* 解法2(推荐解法)
* @param nums 数组
* @param target 目标值
* @return
*/
public int searchInsert1(int[] nums , int target){
int low = 0 , high = nums.length - 1;
while (low <= high){
int mid = low + (high-low)/2;
if(nums[mid] == target) return mid;
else if(nums[mid] > target) high = mid-1;
else low = mid + 1;
}
return low;
}
}