avatar

superorange0707

  • Homepage
  • Tag
  • Category
Home Leetcode-35 -Search Insert Position
文章

Leetcode-35 -Search Insert Position

Posted 2025-04-9
4~6 min read

[35 -Search Insert Position]

🔗 LeetCode Link


Problem Description

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.


Idea

Since the array is sorted, binary search is the most efficient choice (O(log n)).


Logic

  1. Define your search range
  2. Use a loop (while (left <= right) or while (left < right))
  3. Calculate mid, check if target is found
  4. change to the boundary accordingly

Code (Java - Closed Interval)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
    public int searchInsert(int[] nums, int target) {

        int left = 0; int right = nums.length - 1;

        while(left <= right){
            int mid = left + ((right - left)/2);
            
            if(nums[mid] < target){
                left = mid + 1;
            }
            else if(nums[mid] > target){
                right = mid - 1;
            }
            else{
                return mid;
            }
        }
        return right+1;
        
    }
}


Code (Java - Half-Open Interval)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
    public int searchInsert(int[] nums, int target) {

        int left = 0; int right = nums.length;

        while(left < right){
            int mid = left + ((right - left)/2);
            
            if(nums[mid] < target){
                left = mid + 1;
            }
            else if(nums[mid] > target){
                right = mid;
            }
            else{
                return mid;
            }
        }
        return right;
    }
}
Binary Search, Leetcode
Share

Further Reading

Apr 10, 2025

34 - Find First and Last Position of Element in Sorted Array

Apr 10, 2025

367-Valid Perfect Square

Apr 9, 2025

Leetcode-69 - Sqrt(x)

[69 - Sqrt(x)]🔗 LeetCode LinkProblem DescriptionGiven a non-negative integer x, return the square root of x rounded down to the nearest integer. The

OLDER

Fix Personal Website

NEWER

Leetcode-69 - Sqrt(x)

Recently Updated

  • Migrating Jenkins SCM Using GitLab from Bitbucket: SCM URL Bulk Replacement
  • 283 - Move Zero
  • 27 - Remove Element
  • 26 - Remove Duplicates from Sorted Array
  • Migrating from Bitbucket to GitLab? Here’s how to keep your teams moving without missing a beat!

Trending Tags

Course two pointer Binary Tree Hash SQL Leetcode Error Recording Gitlab Bitbucket Devops

Contents

  • Problem Description
  • Idea
  • Logic
  • Code (Java - Closed Interval)
  • Code (Java - Half-Open Interval)