leetcode:Search Insert Position 【Java 】

来源:互联网 发布:心动网络面试题 编辑:程序博客网 时间:2024/05/17 04:02

一、问题描述

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

二、问题分析

借助二分查找算法实现查找插入位置。

三、算法代码

public class Solution {    public int searchInsert(int[] nums, int target) {        int start = 0;        int end = nums.length - 1;        int middle = 0;        while(start <= end){        middle = (start + end)/2;        if(nums[middle] == target){        return middle;        }        if(nums[middle] > target){        end = middle - 1;        }else{        start = middle + 1;        }        }//end while                 if(nums[middle] > target){             return middle;//重点        }else{        return middle + 1;        }    }}




0 0
原创粉丝点击