首页 > 其他分享 >35. Search Insert Position

35. Search Insert Position

时间:2022-11-06 15:56:43浏览次数:37  
标签:Insert Search return target nums int mid 35 low

Given a sorted array 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.

You may assume no duplicates in the array.

Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

 

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

标签:Insert,Search,return,target,nums,int,mid,35,low
From: https://www.cnblogs.com/MarkLeeBYR/p/16862777.html

相关文章