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

 

解题思路:

采用二分法,注意M=(L+R+1)/2的话,会进入死循环。

所以M=(L+R)/2

Final step:wihle loop ends when L=R;

 1 public class Solution {

 2     public int searchInsert(int[] nums, int target) 

 3     {

 4         int left=0;

 5         int right=nums.length-1;

 6         while(left<right)  //final step, left must be equal to right

 7         {

 8             int middle=(left+right)/2;

 9             if(nums[middle]<target)

10             {

11                 left=middle+1;

12             }

13             else

14             {

15                 right=middle;

16             }

17         }

18         

19         return (nums[left]<target)? left+1:left;

20         

21     }

22 }

 

你可能感兴趣的:(position)