Skip to content

Commit cf86626

Browse files
authored
Update readme.md
1 parent ac00bfb commit cf86626

File tree

1 file changed

+40
-1
lines changed
  • src/main/java/g0001_0100/s0035_search_insert_position

1 file changed

+40
-1
lines changed

src/main/java/g0001_0100/s0035_search_insert_position/readme.md

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,43 @@ You must write an algorithm with `O(log n)` runtime complexity.
2929
* <code>1 <= nums.length <= 10<sup>4</sup></code>
3030
* <code>-10<sup>4</sup> <= nums[i] <= 10<sup>4</sup></code>
3131
* `nums` contains **distinct** values sorted in **ascending** order.
32-
* <code>-10<sup>4</sup> <= target <= 10<sup>4</sup></code>
32+
* <code>-10<sup>4</sup> <= target <= 10<sup>4</sup></code>
33+
34+
To solve the "Search Insert Position" problem in Java with a `Solution` class, we can follow these steps:
35+
36+
1. Define a `Solution` class.
37+
2. Define a method named `searchInsert` that takes an integer array `nums` and an integer `target` as input and returns an integer representing the index where `target` would be inserted in order.
38+
3. Implement binary search to find the insertion position of `target`.
39+
4. Set the left pointer `left` to 0 and the right pointer `right` to the length of `nums` minus 1.
40+
5. While `left` is less than or equal to `right`:
41+
- Calculate the middle index `mid` as `(left + right) / 2`.
42+
- If `nums[mid]` is equal to `target`, return `mid`.
43+
- If `target` is less than `nums[mid]`, update `right = mid - 1`.
44+
- If `target` is greater than `nums[mid]`, update `left = mid + 1`.
45+
6. If `target` is not found in `nums`, return the value of `left`, which represents the index where `target` would be inserted in order.
46+
47+
Here's the implementation:
48+
49+
```java
50+
public class Solution {
51+
public int searchInsert(int[] nums, int target) {
52+
int left = 0;
53+
int right = nums.length - 1;
54+
55+
while (left <= right) {
56+
int mid = left + (right - left) / 2;
57+
if (nums[mid] == target) {
58+
return mid;
59+
} else if (target < nums[mid]) {
60+
right = mid - 1;
61+
} else {
62+
left = mid + 1;
63+
}
64+
}
65+
66+
return left;
67+
}
68+
}
69+
```
70+
71+
This implementation provides a solution to the "Search Insert Position" problem in Java. It returns the index where `target` would be inserted in `nums` using binary search, with a time complexity of O(log n).

0 commit comments

Comments
 (0)