您的位置:首页 > 编程语言 > Python开发

python寻找插入位置

2015-01-28 22:35 127 查看
给定一个已经升序排好序的数组,以及一个数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
,最后输入target

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

#include<stdio.h>
#define MAX 10000
int searchInsert(int A[], int n, int target);
int main(){
int n, arr[MAX], target;
scanf("%d",&n);
for(int i = 0; i < n; i++){
scanf("%d",&arr[i]);
}
scanf("%d",&target);
printf("%d\n",searchInsert(arr, n, target));
return 0;
}
int searchInsert(int A[], int n, int target){
int i = 0;
for(; i < n; i++){
if(A[i] >= target)
return i;
}
return i;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐