第12周作业1(LeetCode35)

来源:互联网 发布:腾讯国际足球数据库 编辑:程序博客网 时间:2024/06/16 02:31

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;}
原创粉丝点击