标签:
原题链接在这里:https://leetcode.com/problems/first-bad-version/
尽可能少的使用API, 就想到Binary Search. 查中点是不是,若是bad version, 就在左边继续查,若不是bad version, 就在右边继续查找。
Note: 求中点mid时,要用 mid = left +(right - left)/2, 不能使用 mid = (left + right)/2 因为loop 过程中(left + right)可能超过 Integer.MAX_VALUE, overflow了。
AC Java:
1 /* The isBadVersion API is defined in the parent class VersionControl. 2 boolean isBadVersion(int version); */ 3 4 public class Solution extends VersionControl { 5 public int firstBadVersion(int n) { 6 int left = 1; 7 int right = n; 8 int res = 0; 9 while(left<=right){ 10 int mid = left + (right - left)/2; 11 if(isBadVersion(mid)){ 12 right = mid-1; 13 }else{ 14 left = mid+1; 15 } 16 } 17 return left; 18 } 19 }
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4839898.html