package com.zmz.algorithm.array;

/**
 * @author 张明泽
 * Create by 2022/5/25 11:55
 * 搜索插入位置
 * LeetCode-35
 */
public class SearchInsertionPosition {
    public static void main(String[] args) {
        int[] nums = {1,3,5,7};
        int target = 5;
        int result = searchInsert(nums,target);
        System.out.println(result);
    }
    public static int searchInsert(int[] nums, int target) {
        // 二分法
        int left = 0, right = nums.length - 1;
        while(left <= right){
            // 防止 left+right 整型溢出
            int mid = left + (right - left) / 2;
            if(nums[mid] == target){
                return mid;
            }else if(nums[mid] < target){
                left = mid + 1;
            }else if(nums[mid] > target){
                right = mid - 1;
            }
        }
        return left;
    }
}
最后修改:2022 年 05 月 25 日 12 : 14 PM
赏杯咖啡喝 谢谢您~