计蒜客 挑战难题 第10题:寻找插入位置

来源:互联网 发布:mac怎么设置开机密码 编辑:程序博客网 时间:2024/05/16 13:01

第10题:寻找插入位置

 内存限制 10000 K时间限制 1000 ms

给定一个已经升序排好序的数组,以及一个数target,如果target在数组中,返回它在数组中的位置。


否则,返回target插入数组后它应该在的位置。

假设数组中没有重复的数。以下是简单的示例:

[1,3,5,6], 5 → 2

[1,3,5,6], 2 → 1

[1,3,5,6], 7 → 4

[1,3,5,6], 0 → 0

提示:输入一个整数n,以及其对应的数组A[n],最后输入target

searchInsert(int A[], int n, int target)

样例输入

31 3 52

样例输出

1


仅供参考:

#include <stdio.h>#include <stdlib.h>int searchInsert(int A[],int n,int target);void main(){int *A,n,target;scanf("%d",&n);A=(int*)malloc(n*sizeof(int));for(int i=0;i<n;i++){scanf("%d",&A[i]);}scanf("%d",&target);printf("%d\n",searchInsert(A,n,target));}int searchInsert(int A[],int n,int target){int i;for(i=0;i<n;i++){if(target==A[i])return i;if(target<A[i])return i;}return i;//warning C4715: 'searchInsert' : not all control paths return a value}


1 0