给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。面试题算方法 简单算法 算法面试题

给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。你可以假设数组中无重复元素。

首先先到的是二叉树解法
1 左右两个指针l/r,在定义一个mid中间值,返回值得位置为最大值
2 比较传值与中间值得大小
  2.1 如果小右指针移动到中价值位置在减1,返回值为中间值
  2.2 如果大于中间值左指针移动导中间位置+1

 

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

 

Guess you like

Origin blog.csdn.net/yu1xue1fei/article/details/114267996