Letcode 题:pow(x,n)
2013-03-13 11:39
176 查看
最初的想法,将输入乘以n-1次,时间复杂度为O(n),结果运行结果超时
2.用二分:
xn = xn/2 * xn/2 * xn%2
时间复杂度:O(logN)
这样,使用递归函数,大数据超时
public class Solution { public double pow(double x, int n) { double result = x; double tmp = 1/x; if(n == 0) return 1; if(n > 0){ for(int i = 1; i < n; i++) result = result * x; } else{ for(int j = n; j < -1; j++) result = result * tmp; } return result; } }
2.用二分:
xn = xn/2 * xn/2 * xn%2
时间复杂度:O(logN)
这样,使用递归函数,大数据超时
public double pow(double x, int n) { double result = x; if (x == 0){ if(n == 0) return 1; else return 0; } if (n == 0) return 1; if (n == 1) return x; if (n == -1) return 1/x; if(n >= 2) return pow(x, n / 2) * pow(x, n / 2) * pow(x, n % 2); else{ int absn = Math.abs(n); return 1 / (pow(x, absn / 2) * pow(x, absn / 2) * pow(x, absn % 2)); } }
相关文章推荐
- 使用VS Code开发TypeScript--定义变量推荐使用let
- Let us learn C in Code <3>_constant
- Letcode 198 House Robber
- JavaScript code to let users double-click to move back to the top of the page
- LetCode 412
- 【面试准备】letcode—sort list
- letcode Gray code
- Let us learn C in Code <5>_printf()_function
- Let us learn C in Code <6> _printf()
- PowberBuilder daily code
- Let us learn C in Code <0>
- letcode 118
- Let us learn C in Code <10> flowchart
- LETCODE 165
- openstack 模块eventlet example code
- letcode code]Maximum Subarray
- C# Meta Programming - Let Your Code Generate Code - 利用反射重写自动的ToString()
- codevs5172 装病的聚聚 (最短路spfa的延伸应用)(对三角不等式的深入理解)--by lethalboy
- 【面试准备】letcode—LRU
- jQuery.Hotkeys - lets you watch for keyboard events anywhere in your code supporting almost any key combination