查找插入位置

2018-12-11  本文已影响0人  静水流深ylyang

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

题目大意

给定一个排好序的数组和一个目标值,如果能找到目标值,就返回这个索引。如果不能找到,就返回如果把这个值按需插入的话应该在的位置的索引。

思路

代码

#include<iostream>
using namespace std;
// 暴力查找法
int searchInsert_1(int A[], int n, int target)
{
    for(int i=0; i<n; i++)
    {
        if(A[i] == target) return i;
        if(A[i] > target) return i;
        if(A[i] < target && i == (n-1)) return n;
    }
    return -1;
}
// 二分查找法
int searchInsert(int A[], int n, int target)
{
    int l=0,r=n-1;
    while(l<=r)
    {
        int mid = (l+r)/2;
        if(A[mid] == target)return mid;
        if(A[mid] > target) r = mid-1;
        if(A[mid] < target) l = mid+1;
    }
    return l; // left索引即为需要插入的索引位置
}
int main()
{
    int A[]={1,3,5,6};
    int target=5;
    cout<<searchInsert(A, 4, target)<<endl;

    target=2;
    cout<<searchInsert(A, 4, target)<<endl;

    target=7;
    cout<<searchInsert(A, 4, target)<<endl;

    target=0;
    cout<<searchInsert(A, 4, target)<<endl;
    return 0;
}

运行结果

运行结果
上一篇 下一篇

猜你喜欢

热点阅读