Leet code problem 35
Difficulty: Easy —
Solution
- The question mentioned that the complexity must be
Olog(n)and it’s a search algorithm - We can clearly see that one of the way to solve this is using
Binary searchwith a little modification - Instead of return
-1 (not found)we return theminIndexas the position of thetargetif it exists in thenumsarray
Implementation
Code from github
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class L35_SearchInsertPosition {
public int searchInsert(int[] nums, int target) {
int min = 0;
int max = nums.length - 1;
while (max >= min) {
int mid = min + (max - min) / 2;
if (nums[mid] == target) {
return mid;
} else if (target < nums[mid]) {
max = mid - 1;
} else {
min = mid + 1;
}
}
return min;
}
}