第12周作业1(LeetCode35)

1. 题目描述

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

2. 解决思路

解决这道题首先容易想到顺序遍历数组,因为数组已经是排好序的,所以只要依次比较找到第一个不小于target值的数组元素即可得到target的插入(所在)的位置,这样一来的时间复杂度为O(n),其中n为数组元素的个数(数组长度)。
很显然,这不是最有效的解决办法,进而我们就想到了利用二分查找来解决,这样的时间复杂度降低为O(logn),其他细节可见代码注释。

3. 完整代码

#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;

int BinarySearchInsert(vector<int> &array , int key){
    if (array.back() < key)
        return array.size();

    int begin = 0;
    int end = array.size() - 1;
    while (begin < end)
    {
        int mid = begin + (end - begin) / 2;//避免begin+end的结果溢出
        if (array[mid] > key)
        {
            end = mid;
        }
        else if (array[mid] < key)
        {
            begin = mid + 1;
        }
        else
        {
            return mid;
        }
    }
    return end;
}

int main(){
    vector<int> arr;
    int target = 0;
    int temp = 0;
    cout << "请按从小到大的顺序输入数组arr的各元素:" << endl;

    while (cin >>temp )
    {
        arr.push_back(temp);//注意此行代码与下面if判断的顺序不能调换,否则最后一个temp将不会保存进array
        if (cin.peek() == '\n')
        {
            break;
        }
    }

    cout << "请输入目标值:" << endl;
    cin >> target;
    int result = BinarySearchInsert(arr,target);
    cout << "目标所在或应插入的位置是:\n" << result << endl;

    return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值