c++/java/python 实现二分查找

7 篇文章 0 订阅
4 篇文章 0 订阅

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值