-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchInsertPosition.java
More file actions
53 lines (45 loc) · 1.69 KB
/
SearchInsertPosition.java
File metadata and controls
53 lines (45 loc) · 1.69 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
package Algorithms.BinarySearch;
/**
* Given a sorted array of distinct integers 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
*
* @author Srinivas Vadige, srinivas.vadige@gmail.com
* @since 08 Feb 2025
* @link 35. Search Insert Position <a href="https://leetcode.com/problems/search-insert-position/">LeetCode link</a>
* @topics Array, Binary Search
* @companies Amazon(10), Google(6), Grammarly(3), Meta(2), Microsoft(2), Bloomberg(2), TCS(5), IBM(2), Zoho(2), Accenture(2), Yandex(2), Cognizant(2)
@see DataStructures.BinarySearch
*/
public class SearchInsertPosition {
public static void main(String[] args) {
int[] nums = {1,3,5,6};
int target = 5;
System.out.println("searchInsert(nums, target) => " + searchInsert1(nums, target));
}
/**
* @TimeComplexity O(log n)
* @SpaceComplexity O(1)
*/
public static int searchInsert1(int[] nums, int target) {
int start = 0, end = nums.length - 1, mid = 0;
while (start <= end) {
mid = start + (end - start) / 2;
if (nums[mid] == target) return mid;
else if (nums[mid] < target) start = mid + 1;
else end = mid - 1;
}
return start; // return the index where it would be if it were inserted in order
}
/**
* @TimeComplexity O(log n)
* @SpaceComplexity O(1)
*/
public static int searchInsert2(int[] nums, int target) {
int l = 0, r = nums.length-1;
while(l<=r) {
int mid = l + (r-l)/2;
if (nums[mid] < target) l = mid+1;
else r = mid-1;
}
return l;
}
}