题目:
题目描述
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[] array, int value) {
int high = array.length - 1;
int low = 0,flag = 0;
while(low <= high)
{
int middle = (low + high) / 2;
if(value == array[middle])
{
flag = 1;
return middle;
}
if(value > array[middle])
{
low = middle + 1;
}
if(value < array[middle])
{
high = middle - 1;
}
}
if(flag == 0)
return low;
return -1;
}
}
public class Solution { public int searchInsert(int[] array, int value) { int high = array.length - 1; int low = 0,flag = 0; while(low <= high) { int middle = (low + high) / 2; if(value == array[middle]) { flag = 1; return middle; } if(value > array[middle]) { low = middle + 1; } if(value < array[middle]) { high = middle - 1; } } if(flag == 0) return low; return -1; } }