您的位置:首页 > 其它

[Binary Search]Search Insert Position

2015-12-16 16:32 260 查看
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

分析:将一个数插入到一个有序序列中,要求返回插入点索引。

方法一:直接查找法。由于数组已经是有序的,遍历数组nums,将数组中的元素nums[i]和target进行比较,由于数组是升序的,当target<nums[i],i即为target插入的位置。时间复杂度为O(n)

public int searchInsert(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] >= target)
return i;
}
return nums.length;
}
方法二:使用二分查找。时间复杂度为O(logn)。

public class Solution {
public int searchInsert(int[] nums, int target) {
if (nums.length == 0) {
return 0;
}
int start = 0;
int end = nums.length - 1;
int middle = 0;

while (start <= end) {
middle =start + (end - start) / 2;

if (nums[middle] == target) {
return middle;
} else if (target > nums[middle]) {
start = middle + 1;
} else {
end = middle - 1;
}
}
return start;
}
}


如果数组中不存在和target相当的元素,则当循环结束时,start值即为插入点索引。while循环执行的条件是start <= end,最后一轮循环时,start=end,对于索引为[0, start - 1]的元素,有target < nums[i];

对于索引为[end+1, nums.length - 1]的元素,有target < nums[i]。

因为start=end,所以有middle =
start = end,

当target > nums[middle],start = middle + 1 = end + 1, target < nums[end + 1],start = end + 1,即为target应该插入的位置;

当target < nums[middle],end = middle - 1 = start - 1,target >nums[start + 1],start =

middle,即为target应该插入的位置。

在有序数组中查找插入点的直接查找法和二分查找法,这也是直接插入排序和折半插入排序的基础。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: