[leetcode]Search Insert Position
程序员文章站
2024-03-15 21:34:54
...
新博文地址:[leetcode]Search Insert Position
http://oj.leetcode.com/problems/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
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 int searchInsert(int[] a, int target) {
int begin = 0 ;
int end = a.length - 1;
while(begin <= end){
int mid = ( begin + end ) >> 1;
if(a[mid] == target){
return mid;
}else if(a[mid] > target){
end = mid - 1;
}else{
begin = mid + 1;
}
}
return begin;
}
推荐阅读
-
[LeetCode] Search Insert Position
-
LeetCode——Search Insert Position
-
[leetcode]Search Insert Position
-
【leetcode】35. Search Insert Position 给定数字插入有序数组的下标点
-
[leetcode]Search Insert Position
-
LeetCode: Search Insert Position
-
Search Insert Position -- LeetCode
-
【LeetCode】Search Insert Position
-
[Leetcode] -- Search Insert Position
-
LeetCode 34. 在排序数组中查找元素的第一个和最后一个位置 Find First and Last Position of Element in Sorted Array