J.Gong
2026-12-01
1.18min
This is a very easy binary search problem.
You are given a sorted array nums of distinct integers and a target value. Return the index of target if it is found. If it is not there, return the index where it would have to be inserted to keep nums sorted.
Input: nums = [1,3,5,6], target = 5
Output: 2
Input: nums = [1,3,5,6], target = 2
Output: 1
Input: nums = [1,3,5,6], target = 7
Output: 4
Constraints: , values in , distinct and ascending, . The algorithm must run in .
Normally, I set two pointers, low and high, and cut the range in the middle each time to compare.
class Solution {
public int searchInsert(int[] nums, int target) {
int lo = 0, hi = nums.length;
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if (nums[mid] < target) lo = mid + 1;
else hi = mid;
}
return lo;
}
}
However, the reason I am recording this problem is that binary search has become an auxiliary function that can be called in many languages.
In Python, you can directly call bisect.
from bisect import bisect_left
class Solution:
def searchInsert(self, nums: list[int], target: int) -> int:
return bisect_left(nums, target)
In C#, you can call BinarySearch. If it cannot find the target, it will return the closest index’s two’s complement (in case of index 0).
To get the index, use ~i or -(i+1).
public class Solution {
public int SearchInsert(int[] nums, int target) {
int i = Array.BinarySearch(nums, target);
return i >= 0 ? i: ~i;
}
}
In C++, you can use lower_bound.
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
return int(
lower_bound(
nums.begin(),
nums.end(),
target
) - nums.begin()
);
}
};
Go also supports BinarySearch.
import "slices"
func searchInsert(nums []int, target int) int {
pos, _ := slices.BinarySearch(nums, target)
return pos
}
Rust uses partition_point.
impl Solution {
pub fn search_insert(nums: Vec<i32>, target: i32) -> i32 {
nums.partition_point(|&x| x<target) as i32
}
}