Repository navigation
Expand file tree
/
Copy path35_Search_Insert_Position.java
More file actions
54 lines (50 loc) · 1.72 KB
/
Copy path35_Search_Insert_Position.java
File metadata and controls
54 lines (50 loc) · 1.72 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
/*
* 35. Search Insert Position
* Target: 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.
* Difficulty:Easy
* Classification:Array, Binary Search
*/
/*
* Solution 1
* 2019-07-21 Runtime: 0 ms
* Algorithm: => Divide and Conquer. Note that r = nums.length rather than nums.length - 1, because when there are only two numbers,
* l == mid, which causes infinite loop. There're 2 solutions:
* 1. Change the while loop to "while (l <= r)", change "r = mid" to "r = mid - 1" to prevent l == r infinite loop.
* 2. Change the value of r to "nums.length". So mid will be the right number of two numbers.
* Time Complexity: O(logn), n is the length of string. Space Conplexity: O(1)
*/
class Solution {
public int searchInsert(int[] nums, int target) {
int l = 0, r = nums.length;
if (nums.length == 0) return 0;
while (l < r) {
int mid = (l + r) / 2;
if (target == nums[mid]) {
return mid;
} else if (target > nums[mid]) {
l = mid + 1;
} else {
r = mid;
}
}
return l;
}
}
class Solution {
public int searchInsert(int[] nums, int target) {
int l = 0, r = nums.length - 1;
if (nums.length == 0) return 0;
while (l <= r) {
int mid = (l + r) / 2;
if (target == nums[mid]) {
return mid;
} else if (target > nums[mid]) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return l;
}
}