Sqrt(x)
Sqrt(x)
问题:
Implement int sqrt(int x)
.
Compute and return the square root of x.
思路:
二分查找
我的代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int sqrt(int x) { if(x <=0 ) return 0; int left = 1; int right = (int)Math.ceil(((long)x+1)/2); int rst = -1; long diff = Long.MAX_VALUE; while(left <= right) { int mid = (left + right)/2; long tmp = (long)mid*mid; if(tmp == x) { return mid; } if(tmp > x) right = mid - 1; else { left = mid + 1; if(Math.abs(tmp - x) < diff){ rst = mid; diff = Math.abs(tmp - x); } } } return rst; } }
他人代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Solution { public int sqrt(int x) { if (x == 1 || x == 0) { return x; } int left = 1; int right = x; while (left < right - 1) { int mid = left + (right - left) / 2; int quo = x / mid; if (quo == mid) { return quo; // mid is too big } else if (quo < mid) { right = mid; } else { left = mid; } } return left; } }
学习之处:
- 对于int类型的是,为了考虑到所有的corner case 对于+1 *2 等操作一定要转换成Long 类型再做,要不溢出啦!溢出啦!
- 抓住一个特点:(int)√x*(int)√x ≤ x 不可能出现在大的那一边的
- 没有必要跟踪和更新最小值的操作的right节点right会指向趋近点的,其实仔细想一想也就明白了,没想明白就需要多写了好多代码!
- 这道题刚开始没思路,想了想就有思路了,多想才是王道。
posted on 2015-03-31 21:54 zhouzhou0615 阅读(173) 评论(0) 编辑 收藏 举报