c++/java/python 实现二分查找
题目:寻找插入位置
给定一个已经升序排好序的数组,以及一个数target,如果target在数组中,返回它在数组中的位置。否则,返回target插入数组后它应该在的位置。
提示:输入一个整数n,以及其对应的数组A[n],最后输入target
C++
#include <iostream>
#include <cstdio>
int searchInsert(int A[], int n, int target){
int left = 0, right = n - 1;
int mid;
while(left < right){
mid = (left + right) / 2;
if(target <= A[mid]){
right = mid;
}else{
left = mid + 1;
}
}
if(target >= A[left]){
left ++;
}
return left;
}
int main(){
int n, target;
scanf("%d", &n);
int A[n];
for(int i = 0; i < n; i++){
scanf("%d", &A[i]);
}
scanf("%d", &target);
printf("%d", searchInsert(A, n, target));
}
java
import java.util.Scanner;
public class Main{
public int searchInsert(int[] A, int n, int target){
int left = 0, right = n - 1, mid;
while(left < right){
mid = (left + right) / 2;
if(target <= A[mid]){
right = mid;
}else{
left = mid + 1;
}
}
if(target > A[left]){
left ++;
}
return left;
}
public static void main(String args[]){
Main main = new Main();
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] A = new int[n];
for(int i = 0; i < n; i++){
A[i] = scan.nextInt();
}
int target = scan.nextInt();
System.out.println(main.searchInsert(A, n, target));
}
}
python
def searchInsert(A, n, target):
left = 0
right = n - 1
while left < right:
mid = (left + right) / 2
if target <= A[mid]:
right = mid
else:
left = mid + 1
if target >= A[left]:
left += 1
return left
if __name__ == "__main__":
n = int(raw_input())
A = [int(i) for i in raw_input().split()]
target = int(raw_input())
print searchInsert(A, n, target)