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.
Example:
Input: [1,3,5,6], 5
Output: 2
Input: [1,3,5,6], 2
Output: 1
Input: [1,3,5,6], 7
Output: 4
Input: [1,3,5,6], 0
Output: 0
Note:
You may assume no duplicates in the array.
解釋下題目:
給定一個排好序的數(shù)組锌仅,在給定一個數(shù)字,如果這個數(shù)字在這個數(shù)組中,返回它的下標哈街,否則就把它插入到正確的位置,返回那個位置的下標。
1. 二分查找法
實際耗時:5ms
public int searchInsert(int[] nums, int target) {
//二分查找法
int small = 0;
int big = nums.length - 1;
int medium;
while (big >= small) {
medium = (small + big) / 2;
if (target == nums[medium]) {
return medium;
} else if (target > nums[medium]) {
small = medium + 1;
} else {
big = medium - 1;
}
}
//return nums[medium] > target ? medium : medium + 1;
return small;
}
??思路就是二分查找,找到就返回下標窄坦。沒找到就應(yīng)該返回small的,因為應(yīng)該插入到small這個位置凳寺。當然用個判斷可能更容易理解