69. Sqrt(x)
题目
分析,题目实现求一个int数的平方根,最暴力的算法就是逐个遍历,从1开始到x,判断是否有一个数i,其中满足i*i<=x,并且(i+1)*(i+1)>x;这个算法发虽然简单,但是效率不高。其实,按照暴力算法的思想,我们可以联想到在一个已经排好序的数组中查找一个数,该数正好满足上面的条件,因此可以采用二分查找的思想。代码如下:
1 class Solution { 2 public: 3 int mySqrt(int x) { 4 int a[10]={0,1,1,1,2,2,2,2,2,3}; 5 if(x<=9) 6 return a[x]; 7 8 unsigned long long left=1,right=x; 9 10 unsigned long long middle= (left + right)>>1; 11 while(left<=right) 12 { 13 middle = (left + right)>>1; 14 if(middle * middle <x) 15 { 16 left = middle+1; 17 18 } 19 else if(middle * middle > x) 20 { 21 right = middle - 1; 22 23 } 24 else 25 return middle; 26 } 27 if(middle * middle > x) 28 middle--; 29 //if(middle * middle < x) 30 // middle++; 31 return middle; 32 } 33 };
------------------------------------------------------------------------分割线--------------------------------------------------------------------------
70. Climbing Stairs
题目
分析:费波拉契数列
代码如下:
1 class Solution { 2 public: 3 int climbStairs(int n) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 7 if(n <= 2) 8 { 9 return n; 10 } 11 else 12 { 13 int* step = new int[n]; 14 15 step[0] = 1; 16 step[1] = 2; 17 18 for(int i = 2; i < n; i++) 19 { 20 step[i] = step[i-1] + step[i-2]; 21 } 22 return step[n-1]; 23 } 24 } 25 };
-------------------------------------------------------------------------------分割线----------------------------------------------------------------
71. Simplify Path
提示:简单的字符串操作,其基本思想是将path按照‘\‘进行截取,并将截取后的字符串压栈。
代码如下:
1 class Solution { 2 public: 3 string simplifyPath(string path) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 stack<string> s; 7 string str; 8 for(int i = 0; i < path.size(); i++) 9 { 10 if (path[i] == ‘/‘) 11 { 12 if (str == "..") 13 { 14 if (!s.empty()) 15 s.pop(); 16 } 17 else if (str != "." && str != "") 18 { 19 s.push(str); 20 } 21 22 str = ""; 23 } 24 else 25 { 26 str += path[i]; 27 } 28 } 29 30 if (str == "..") 31 { 32 if (!s.empty()) 33 s.pop(); 34 } 35 else if (str != "." && str != "") 36 s.push(str); 37 38 if (s.empty()) 39 return "/"; 40 41 string ret; 42 while(!s.empty()) 43 { 44 ret = "/" + s.top() + ret; 45 s.pop(); 46 } 47 48 return ret; 49 } 50 };
时间: 2024-10-04 22:32:02