35. Search Insert Position java solutions

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

Subscribe to see which companies asked this question

 1 public class Solution {
 2     public int searchInsert(int[] nums, int target) {
 3         int ans = 0;
 4         for(int i = 0;i < nums.length; i++){
 5             if(nums[i] >= target) {
 6                 ans = i;
 7                 break;
 8             }
 9             else if(nums[i] < target){
10                 ans = i+1;
11                 continue;
12             }
13         }
14         return ans;
15     }
16 }

最简单遍历一遍,

不过题目很明显,可以用二分法。

代码:

 1 public class Solution {
 2     public int searchInsert(int[] nums, int target) {
 3         if(nums.length == 0 || nums == null) return 0;
 4         int low = 0,high = nums.length - 1;
 5         while(low <= high){
 6             int mid = (low + high)/2;
 7             if(nums[mid] == target) return mid;
 8             else if(nums[mid] < target){
 9                 low = mid + 1;
10             }else
11                 high = mid - 1;
12         }
13         return low;
14     }
15 }
原文地址:https://www.cnblogs.com/guoguolan/p/5611485.html