[Algorithm problem solution] LeetCode 35 search insertion position

topic

Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, return the position where it will be inserted in order.

You can assume that there are no duplicate elements in the array.

answer

This problem can be solved using a basic binary search algorithm. Just need to pay attention to the condition of returning to the position that should be inserted when the target value does not exist in the array. This is how I judge this condition. Because the last comparison with target is nums[mid], the target value must be inserted before or after mid, so just judge the relationship with mid, and then consider the situation when mid is the boundary.

Code

class Solution {
    public int searchInsert(int[] nums, int target) {
        int start = 0,end = nums.length - 1;
        int mid = 0;
        while(start <= end) {
            mid = start + (end - start) / 2;
            if(nums[mid] == target) {
                return mid;
            } else if(nums[mid] > target) {
                end = mid -1;
            } else {
                start = mid + 1;
            }
        }
        mid = (nums[mid] > target) ? mid : mid + 1;
        return mid;
    }
}

Guess you like

Origin blog.csdn.net/vxzhg/article/details/106748528