LeetCode简单题:278. 第一个错误的版本(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/first-bad-version/
要点:二分法
Python,C++,Java都用了二分法。
本题是找两堆版本的分界处,每次找中间位置然后调整left和right位置,最好画图判断边界是左边还是右边。

二.Python实现

# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):

class Solution:
    def firstBadVersion(self, n):
        """
        :type n: int
        :rtype: int
        """
        left = 1
        right = n
        while left <= right:
            midpoint = (left+right) // 2
            if not isBadVersion(midpoint):
                left = midpoint + 1
            else:
                right = midpoint - 1  
        return left

三.C++实现

// The API isBadVersion is defined for you.
// bool isBadVersion(int version);

class Solution {
public:
    int firstBadVersion(int n) {
        int left,right,mid;
        left=1;
        right=n;
        while(left

四.java实现

/* The isBadVersion API is defined in the parent class VersionControl.
      boolean isBadVersion(int version); */

public class Solution extends VersionControl {
    public int firstBadVersion(int n) {
        int left,right,mid;
        left=1;
        right=n;
        while(left

你可能感兴趣的:(LeetCode简单题:278. 第一个错误的版本(Python,C++,Java))