程序媛詹妮弗
终身学习

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 4:

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

 

题意:

给定有序数组和一个target,寻找合适的插入位置。

 

Solution1: Binary Search

数组元素有偶数个时, 中点若取偏左端的那个

1   2   3   4

        ^mid

那么,更新left时,从mid + 1 开始

 

code:

 1 /*
 2 Time: O(log(n))
 3 Space: O(1)
 4 */
 5 class Solution {
 6    public int searchInsert(int[] nums, int target) {
 7         //corner case
 8         if (nums == null || nums.length == 0) {
 9             return 0;
10         }
11         if (target < nums[0]) {   //[1,3,5,6], 0
12             return 0;
13         } else if (target > nums[nums.length - 1]) {  // [1,3,5,6], 7
14             return nums.length;
15         }
16         // binary search
17         int left = 0, right = nums.length - 1;
18         while (left < right) {
19             int mid = left + (right - left) / 2;
20             if (nums[mid] == target) {
21                 return mid;
22             } else if (nums[mid] > target) {
23                 right = mid;
24             } else {
25                 left = mid + 1;
26             }
27         }
28         return left;
29     }
30 }

 

posted on 2019-04-12 05:44  程序媛詹妮弗  阅读(175)  评论(0编辑  收藏  举报