LeetCode First Bad Version
2015-09-26 02:06
274 查看
原题链接在这里: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:
尽可能少的使用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:
/* 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 = 1; int right = n; int res = 0; while(left<=right){ int mid = left + (right - left)/2; if(isBadVersion(mid)){ right = mid-1; }else{ left = mid+1; } } return left; } }
相关文章推荐
- C | 位域&联合体
- 获取一个数二进制序列中所有的偶数位和奇数位,分别输出二进制序列。
- 11、vim的基本使用和技巧
- shell脚本学习 三
- win8.1安装apache+php
- 简单的交换两个数组的内容
- [思路贪心]UVa12545 - Bits Equalizer
- Mysql 列转行统计查询 、行转列统计查询
- C# 6.0 黑科技
- 一、ArrayList概述
- LeetCode Container With Most Water
- java 在linux下获取的时间是美国时间,解决办法
- C++ | STL 概述
- HashCode和equal方法的区别和联系
- ios8 UITableVIewCell 侧滑显示多个按钮
- Fragment Or DialogFragment Can not perform this action after onSaveInstanceState
- git commit
- 史上最全最强SpringMVC详细示例实战教程
- Eclipse中配置Servlet流程
- hdoj1798Tell me the area【求两圆相交部分的面积】