首页 > 其他分享 >SearchInsert

SearchInsert

时间:2023-04-03 23:01:16浏览次数:38  
标签:target int 数组 目标值 public SearchInsert

package BisectionMethod;

/**
 * 35. 搜索插入位置
 * 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
 * 请必须使用时间复杂度为 O(log n) 的算法。
 *
 * */
public class SearchInsert {
    public static void main(String[] args) {
        int [] arr = {1,3,5,7,9,11};
        int target = 12;
        int result = searchInsert(arr,target);
        System.out.println(result);

    }
    public static int searchInsert(int[] nums, int target) {
        int left = 0, right = nums.length - 1;
        while(left <= right) {
            int mid = (left + right) / 2;
            if(nums[mid] == target) {
                return mid;
            } else if(nums[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return left;
    }
}

 

标签:target,int,数组,目标值,public,SearchInsert
From: https://www.cnblogs.com/lipinbigdata/p/17284821.html

相关文章