您的位置:首页 > 其它

LeetCode-Easy部分中标签为Array#35: Search Insert Position

2017-03-27 21:59 447 查看

原文

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

题目意思

确定一个有序数组中,插入目标值的索引位置,如果插入值已经存在,则直接返回它的索引值,如果不存在,确定插入后的索引位置。

题目分析

利用二查搜索非递归方法,拿target元素与中点位置的元素做比较,

如果不大于中间元素,区间缩小为[lo,hi];

如果小于中间元素,区间缩小为 [lo+1,hi);

递归方法:

target与 中间元素比较,

若相等,则返回,

若小于中间元素,则在左区间递归([lo,mi))

否则在右区间递归((mi,hi))

代码实现

1 二查搜索

关于这个二查搜索的解题思路,请参考我的总结:

有序数组中利用压缩思想

这是非常精简的一种二查搜索算法,非递归版。

public class Solution {
public int SearchInsert(int[] nums, int target) {
int lo = 0;
int hi = nums.Length;
while(lo<hi){
int mi = (lo+hi)>>1;
if(target<=nums[mi]) //目标值不大于中间位置的数时,hi变小
hi=mi;
else if(target>nums[mi]) //大于中间位置的值,lo加1
lo=lo+1;
}
return lo;
}
}


2 二查搜索递归版

这个算法比第一种方法好理解。

int search(int A[], int start, int end, int target) {
if (start > end) return start;
int mid = (start + end) / 2;
if (A[mid] == target) return mid;
else if (A[mid] > target) return search(A, start, mid - 1, target);
else return search(A, mid + 1, end, target);
}
int searchInsert(int nums[],int target) {
return search(nums, 0, nums.Length - 1, target);
}


更多LeetCode题目

LeetCode-题目按tag分类

LeetCode-Easy部分中标签为Array的所有题目
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: