forked from soulmachine/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 97
/
chapDivideAndConquer.tex
90 lines (67 loc) · 1.71 KB
/
chapDivideAndConquer.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
\chapter{分治法}
\section{Pow(x,n)} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:pow}
\subsubsection{描述}
Implement pow(x, n).
\subsubsection{分析}
二分法,$x^n = x^{n/2} \times x^{n/2} \times x^{n\%2}$
\subsubsection{代码}
\begin{Code}
//LeetCode, Pow(x, n)
// 二分法,$x^n = x^{n/2} * x^{n/2} * x^{n\%2}$
class Solution {
public:
double pow(double x, int n) {
if (n < 0) return 1.0 / power(x, -n);
else return power(x, n);
}
private:
double power(double x, int n) {
if (n == 0) return 1;
double v = power(x, n / 2);
if (n % 2 == 0) return v * v;
else return v * v * x;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Sqrt(x),见 \S \ref{sec:sqrt}
\myenddot
\section{Sqrt(x)} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\label{sec:sqrt}
\subsubsection{描述}
Implement int \fn{sqrt(int x)}.
Compute and return the square root of \fn{x}.
\subsubsection{分析}
二分查找
\subsubsection{代码}
\begin{Code}
// LeetCode, Longest Substring Without Repeating Characters
// 二分查找
class Solution {
public:
int sqrt(int x) {
int left = 1, right = x / 2;
int mid;
int last_mid; // 记录最近一次mid
if (x < 2) return x;
while(left <= right) {
mid = left + (right - left) / 2;
if(x / mid > mid) { // 不要用 x > mid * mid,会溢出
left = mid + 1;
last_mid = mid;
} else if(x / mid < mid) {
right = mid - 1;
} else {
return mid;
}
}
return last_mid;
}
};
\end{Code}
\subsubsection{相关题目}
\begindot
\item Pow(x),见 \S \ref{sec:pow}
\myenddot