Home Leetcode 35. Search Insert position
Post
Cancel

Leetcode 35. Search Insert position

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 search with a little modification
  • Instead of return -1 (not found) we return the minIndex as the position of the target if it exists in the nums array

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;
    }
}
This post is licensed under CC BY 4.0 by the author.