注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
前两期
双指针:https://www.1point3acres.com/bbs/thread-1006177-1-1.html贪心算法:https://www.1point3acres.com/bbs/thread-1006359-1-1.html
新人找工作求大米看面经QAQ 加米是我持续更新的动力 感谢!!!
题目链接:https://leetcode.com/problems/sqrtx/description/
思路:二分法 Binary Search
初步思路:
如果 n * n = x 就return n;
如果 n * n < x 就 l = m+1;
如果 n * n > x 就 h = m-1。
Edge conditions:
1. x可以等于0,所以l要从0开始,h=x (根号1=1)。
2. x 可以是很大的数,所以l和m要用long declare。
3. 同时考虑: 何时退出循环? -- while循环的条件是?
4. l 和 h的初始条件是?
一般的二分查找法:`int l = 0, h = nums.length - 1;` 可见l到h之间的数字的个数与array里面element的个数一样。
问题:如果sqr (x) 为非整数,比如根号2,就无法得出正确结果。此时返回什么值?
假设: l=0,h=x-1。
Edge Condition:x=1,return 1。x=0, return 0。
(x=8):
* l=0, h=7, m=3。-> h= 3-1=2;
* l=0, h=2, m=1。 -> l=1+1=2;
* l=2, h=2, m=2。 -> l=2+1=3
l>h, 退出循环,return h。循环终止条件:l<=h。
class Solution {
public:
int mySqrt(int x) {
if(x<=1){
return x;
}
/* 使用long来表示大数字。*/
long l=0;
long h=x-1;
/* 可以不在外面declare,在循环里面declare。*/
//int m=0;
while (l<=h){
/* 直接在循环里面declare 没问题,因为m没有储存的意义。*/
// m=l+(h-l)/2;
int m=l+(h-l)/2;
if (m*m==x){
return m;
}
else if (m*m<x){
l=m+1;
}
else{
h=m-1;
}
}
return h;
}
};
以上代码可以解决大部分test case,但是当x很大时,m * m 的结果会超出字符限制。
解决方法:n * n =x 改为 x/n=n (整除符号自动取整)。
假设 l=0,h=x-1: x/m时m不能为0。但是如果x=2时,m会等于0 (l=0, h=1,m=0)
解决办法:初始条件里的l和m都加1。
class Solution {
public:
int mySqrt(int x) {
if(x<=1){
return x;
}
/* 使用long来表示大数字。*/
long l=1;
long h=x;
/* 可以不在外面declare,在循环里面declare。*/
//int m=0;
while (l<=h){
/* 直接在循环里面declare 没问题,因为m没有储存的意义。*/
// m=l+(h-l)/2;
int m=l+(h-l)/2;
if (x/m==m){
return m;
}
else if (x/m>m){
l=m+1;
}
else{
h=m-1;
}
}
return h;
}
}; |