Search Insert Position

来源:互联网 发布:ibatis log4j sql 编辑:程序博客网 时间:2024/06/02 02:50

Description:

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.

Ex:

[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0

问题描述

搜索插入位置,给定目标元素和递增数组(不存在重复元素),如果目标元素在数组中,则返回索引。。否则返回应该插入位置的索引。。

解法一:

思路:

典型的二分查找问题,寻找下届的变种。。。

Code:

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