您的位置:首页 > 编程语言 > Java开发

leetcode:Search Insert Position 【Java 】

2016-03-03 13:21 393 查看
一、问题描述

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;
        }
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: