給定一個已經升序排好序的數組,以及一個數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)
樣例1
輸入:
3
1 3 5
2
輸出:
1
#include <stdio.h>
#include <malloc.h>
int searchInsert(int A[], int n, int target){
int low = 0;
int high = n - 1;
int index; //未查找到時顯示應該插入的索引
//使用二分查找target在不在A中
while(low <= high)
{
int mid = (low + high)/2;
if(A[mid] == target)
{
return mid;
}else if(A[mid] < target)
{
low = mid + 1;
index = low;
}else{
high = mid - 1;
index = high + 1;
}
}
return index;
}
int main(int argc, char **argv) {
int i,n,result,target;
scanf("%d",&n);
int *a = (int *)malloc(n * sizeof(int));
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
scanf("%d",&target);
result = searchInsert(a,n,target);
printf("%d",result);
return 0;
}