LeetCode 50 題解

兩種方式都爲通過,很奇怪,超時

/**
 * 類說明 實現 pow(x, n) ,即計算 x 的 n 次冪函數。
 * 
 * 示例 1:
 * 
 * 輸入: 2.00000, 10 輸出: 1024.00000
 * 
 * 示例 2:
 * 
 * 輸入: 2.10000, 3 輸出: 9.26100
 * 
 * 示例 3:
 * 
 * 輸入: 2.00000, -2 輸出: 0.25000 解釋: 2-2 = 1/22 = 1/4 = 0.25
 * 
 * 來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/powx-n
 * 著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
 * 
 * <pre>
 * Modify Information:
 * Author        Date          Description
 * ============ =========== ============================
 * wangm          2020年5月14日    Create this file
 * </pre>
 * 
 */

public class LeetCode50 {

    
    public double myPow(double x, int n) {
        if(x == 1|| x== -1 ){
            return x;
        }
        if(n == 0){
            return 1;
        }
        if (n < 0) {
            x = 1 / x;
            n = -n;
        }
        double pow = 1.0;
        while (n != 0) {
            if ((n & 1) == 1) {
                pow *= x;
            }
            x *= x;
            n >>= 1;
        }
        return pow;
    }
    public double myPow1(double x, int n) {
        if (n == 0) {
            return 1;
        }
        if(x == 1){
            return 1;
        }
        if (n < 0) {
            return 1.0 / myPow1(x, -n);
        }
        if (n % 2 == 0) {
//            return myPow(x, n >> 1)*myPow(x, n >> 1); 會超時
            return myPow1(x*x, n >> 1);
        }
//        return x * myPow(x, n >> 1)*myPow(x, n >> 1);
        return x * myPow1(x*x, n >> 1);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(new LeetCode50().myPow(2, 10));
        System.out.println(new LeetCode50().myPow(2, -2));
        System.out.println(new LeetCode50().myPow(2.1, 3));
    }

}

分治算法模板

def divide_comquer(problem, param1, parana, ... )

#recursion terminator 
if problem is None:
    print result
return 
# prepare data 
data =  prepare_data(problem)
spLit_problems = split_problem(problem_data)
# conquer subproblems
subresult1 = self.divide_conquer(subproblems[0],p1,...)
subresult2 self.divide_conquer(subproblems[l], pl,...)
subresult3= self.divide_conquer(subproblems[2], pl,...)
... 
# proress anmd generate the FInal nesult 
result = process_ result(subresultl, subresult2, subresult3, ...)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章