Leetcode题解(23)

时间:2021-03-07 08:16:33

69. Sqrt(x)

题目

Leetcode题解(23)

分析,题目实现求一个int数的平方根,最暴力的算法就是逐个遍历,从1开始到x,判断是否有一个数i,其中满足i*i<=x,并且(i+1)*(i+1)>x;这个算法发虽然简单,但是效率不高。其实,按照暴力算法的思想,我们可以联想到在一个已经排好序的数组中查找一个数,该数正好满足上面的条件,因此可以采用二分查找的思想。代码如下:

 class Solution {
public:
int mySqrt(int x) {
int a[]={,,,,,,,,,};
if(x<=)
return a[x]; unsigned long long left=,right=x; unsigned long long middle= (left + right)>>;
while(left<=right)
{
middle = (left + right)>>;
if(middle * middle <x)
{
left = middle+; }
else if(middle * middle > x)
{
right = middle - ; }
else
return middle;
}
if(middle * middle > x)
middle--;
//if(middle * middle < x)
// middle++;
return middle;
}
};

------------------------------------------------------------------------分割线--------------------------------------------------------------------------

70. Climbing Stairs

题目

Leetcode题解(23)

分析:费波拉契数列

代码如下:

 class Solution {
public:
int climbStairs(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function if(n <= )
{
return n;
}
else
{
int* step = new int[n]; step[] = ;
step[] = ; for(int i = ; i < n; i++)
{
step[i] = step[i-] + step[i-];
}
return step[n-];
}
}
};

-------------------------------------------------------------------------------分割线----------------------------------------------------------------

71. Simplify Path

Leetcode题解(23)

提示:简单的字符串操作,其基本思想是将path按照'\'进行截取,并将截取后的字符串压栈。

代码如下:

 class Solution {
public:
string simplifyPath(string path) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<string> s;
string str;
for(int i = ; i < path.size(); i++)
{
if (path[i] == '/')
{
if (str == "..")
{
if (!s.empty())
s.pop();
}
else if (str != "." && str != "")
{
s.push(str);
} str = "";
}
else
{
str += path[i];
}
} if (str == "..")
{
if (!s.empty())
s.pop();
}
else if (str != "." && str != "")
s.push(str); if (s.empty())
return "/"; string ret;
while(!s.empty())
{
ret = "/" + s.top() + ret;
s.pop();
} return ret;
}
};