Skip to content

Commit e4228e7

Browse files
committed
纠正复杂度,添加代码1
1 parent afe4bba commit e4228e7

File tree

2 files changed

+41
-3
lines changed

2 files changed

+41
-3
lines changed

C++/LeetCodet题解(C++版).pdf

831 Bytes
Binary file not shown.

C++/chapLinearList.tex

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -498,13 +498,51 @@ \subsubsection{描述}
498498

499499

500500
\subsubsection{分析}
501-
先排序,然后左右夹逼,复杂度 $O(n^3)$
501+
先排序,然后左右夹逼,复杂度 $O(n^2)$
502502

503503

504-
\subsubsection{代码}
504+
\subsubsection{代码1}
505+
\begin{Code}
506+
// LeetCode, 3Sum Closest
507+
// 先排序,然后左右夹逼,时间复杂度O(n^2),空间复杂度O(1)
508+
class Solution {
509+
public:
510+
int threeSumClosest(vector<int>& num, int target) {
511+
int result = 0;
512+
int min_gap = INT_MAX;
513+
514+
sort(num.begin(), num.end());
515+
516+
for (auto a = num.begin(); a != prev(num.end(), 2);
517+
a = upper_bound(a, prev(num.end(), 2), *a)) {
518+
auto b = next(a);
519+
auto c = prev(num.end());
520+
521+
while (b < c) {
522+
const int sum = *a + *b + *c;
523+
const int gap = abs(sum - target);
524+
525+
if (gap < min_gap) {
526+
result = sum;
527+
min_gap = gap;
528+
}
529+
530+
if (sum < target) ++b;
531+
else --c;
532+
}
533+
}
534+
535+
return result;
536+
}
537+
};
538+
\end{Code}
539+
540+
541+
\subsubsection{代码2}
505542
\begin{Code}
506543
// LeetCode, 3Sum Closest
507-
// 先排序,然后左右夹逼,时间复杂度O(n^3),空间复杂度O(1)
544+
// 先排序,然后左右夹逼
545+
// 时间复杂度O(n^2),空间复杂度O(1),与代码1比,有常数级的优化
508546
class Solution {
509547
public:
510548
int threeSumClosest(vector<int>& num, int target) {

0 commit comments

Comments
 (0)