# leetCode 35.Search Insert Position (搜索插入位置) 解题思路和方法

Search Insert Position

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) {
//特殊情况
if(nums.length == 0 || nums[0] > target)
return 0;
if(nums[nums.length - 1] < target)
return nums.length;
//先二分查找，找到了就返回
int low = 0;
int hight = nums.length - 1;
int mid = 0;
while(low <= hight){
mid = (low + hight)/2;
if(nums[mid] < target){
low = mid + 1;
}else if(nums[mid] > target){
hight = mid - 1;
}else{
return mid;
}
}
//找不到再判断与nums[mid]大小，返回索引
return nums[mid] > target?mid:mid+1;
}
}

• 本文已收录于以下专栏：

## 【LeetCode-面试算法经典-Java实现】【035-Search Insert Position（搜索插入位置）】

【035-Search Insert Position（搜索插入位置）】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题　　Given a sorted array and a...

## LeetCode | Search Insert Position（查找插入位置）

Given a sorted array and a target value, return the index if the target is found. If not, return the...

## [LeetCode]35.Search Insert Position

【题目】 Given a sorted array and a target value, return the index if the target is found. If not, ...

## LeetCode 35 Search Insert Position (C,C++,Java,Python)

Problem: Given a sorted array and a target value, return the index if the target is found. If n...

## LeetCode 35. Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the...

## [LeetCode35]Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the...
• sbitswc
• 2014年06月16日 04:11
• 589

## <LeetCode OJ> 35. Search Insert Position

35. Search Insert Position My Submissions Question Total Accepted: 94638 Total Submissions: 2569...

举报原因： 您举报文章：leetCode 35.Search Insert Position (搜索插入位置) 解题思路和方法 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)