LeetCode-Easy部分中标签为Array#35: 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


题目意思

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


题目分析

利用二查搜索非递归方法,拿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的所有题目

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值