-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchInsertPosition.java
More file actions
39 lines (34 loc) · 960 Bytes
/
SearchInsertPosition.java
File metadata and controls
39 lines (34 loc) · 960 Bytes
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
package com.leetcode;
/**
* Created by jamylu on 2018/1/3.
* leetcode035
*/
public class SearchInsertPosition {
public static void main(String[] args) {
int[] nums = {1, 3, 5, 6};
int target = 7;
System.out.println(BinSearchInsert(nums, target));
}
//二分搜索
public static int BinSearchInsert(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (high >= low) {
int mid = (low + high) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
low = mid + 1;
} else
high = mid - 1;
}
return low;
}
// 直接遍历,O(n)
public static int searchInsert(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] >= target)
return i;
}
return nums.length;
}
}