50. pow(x, n)
這道題要用遞迴,但是遞迴不能用乙個個減,因為這樣要是碰到很大的n的情況會有stack overflow error。所以要利用平方,一次變成n / 2。
public class solution
double powv = mypow(x, n / 2);
if (n % 2 != 0)
else
}else
}}
69. sqrt(x)
這道題也是用二分法。注意邊界條件,還有要防止輸入乙個很大的數,所以要用long形式。
public class solution
return (int)find(x, 0, x);
}private long find(long x, long lo ,long hi)
long mid = lo + (hi - lo) / 2;
if (mid * mid > x)
else if (mid * mid < x)
else
}}
275. h-index ii
二分法輕鬆·搞定
public class solution
else if (citations[mid] < len - mid)
else
}return len - lo;
}}
LeetCode刷題實戰201 數字範圍按位與
given a range m,n where 0 m n 2147483647,return the bitwise and of all numbers in this range,inclusive.給定範圍 m,n 其中 0 m n 2147483647,返回此範圍內所有數字的按位與 包含 ...
Leetcode刷題筆記
1.兩數之和給定乙個整數陣列nums 和乙個目標值target,請你在該陣列中找出和為目標值的那兩個整數,並返回他們的陣列下標。ps 你可以假設每種輸入只會對應乙個答案。但是,你不能重複利用這個陣列中同樣的元素。思路 用target減去nums中的每乙個數,並設立乙個字典來記錄對應的下標 class...
LeetCode刷題筆記
實現strstr 給定乙個 haystack 字串和乙個 needle 字串,在 haystack 字串中找出 needle 字串出現的第乙個位置 從0開始 如果不存在,則返回 1。示例 1 輸入 haystack hello needle ll 輸出 2 示例 2 輸入 haystack aaaa...