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 index where it would be if it were inserted in order.

You may assume no duplicates in the array.

Example 1:

Input: [1,3,5,6], 5
Output: 2

 

Example 2:

Input: [1,3,5,6], 2
Output: 1

 

Example 3:

Input: [1,3,5,6], 7
Output: 4

 

Example 1:

Input: [1,3,5,6], 0
Output: 0



 1 public class Solution {
 2     public int SearchInsert(int[] nums, int target) {
 3         int low = 0, high = nums.Length;
 4         
 5         while (low < high)
 6         {
 7             int mid = low + (high - low) / 2;
 8             
 9             if (nums[mid] == target)
10             {
11                 return mid;
12             }
13             else if (nums[mid] < target)
14             {
15                 if (mid < nums.Length - 1 && target < nums[mid + 1])
16                 {
17                     return mid + 1;
18                 }
19                 
20                 low = mid + 1;
21             }
22             else
23             {
24                 if (mid > 0 && target > nums[mid - 1])
25                 {
26                     return mid;
27                 }
28                 
29                 high = mid;
30             }
31         }
32         
33         return low;
34     }
35 }

 

posted @ 2017-11-06 04:48  逸朵  阅读(124)  评论(0编辑  收藏  举报