Skip to content

Commit 09a93c9

Browse files
committed
fix 3Sum TLE
1 parent 5cbeb1b commit 09a93c9

File tree

3 files changed

+17
-58
lines changed

3 files changed

+17
-58
lines changed

C++/chapLinearList.tex

+17-58
Original file line numberDiff line numberDiff line change
@@ -547,78 +547,37 @@ \subsubsection{分析}
547547
\subsubsection{代码}
548548
\begin{Code}
549549
// LeetCode, 3Sum
550-
// 先排序,然后左右夹逼,时间复杂度O(n^2),空间复杂度O(1)
550+
// 先排序,然后左右夹逼,注意跳过重复的数,时间复杂度O(n^2),空间复杂度O(1)
551551
class Solution {
552-
public:
552+
public:
553553
vector<vector<int>> threeSum(vector<int>& num) {
554554
vector<vector<int>> result;
555555
if (num.size() < 3) return result;
556556
sort(num.begin(), num.end());
557557
const int target = 0;
558-
558+
559559
auto last = num.end();
560-
for (auto a = num.begin(); a < prev(last, 2); ++a) {
561-
auto b = next(a);
562-
auto c = prev(last);
563-
while (b < c) {
564-
if (*a + *b + *c < target) {
565-
++b;
566-
} else if (*a + *b + *c > target) {
567-
--c;
560+
for (auto i = num.begin(); i < last-2; ++i) {
561+
auto j = i+1;
562+
if (i > num.begin() && *i == *(i-1)) continue;
563+
auto k = last-1;
564+
while (j < k) {
565+
if (*i + *j + *k < target) {
566+
++j;
567+
while(*j == *(j - 1) && j < k) ++j;
568+
} else if (*i + *j + *k > target) {
569+
--k;
570+
while(*k == *(k + 1) && j < k) --k;
568571
} else {
569-
result.push_back({ *a, *b, *c });
570-
++b;
571-
--c;
572-
}
573-
}
574-
}
575-
sort(result.begin(), result.end());
576-
result.erase(unique(result.begin(), result.end()), result.end());
577-
return result;
578-
}
579-
};
580-
\end{Code}
581-
582-
\subsubsection{分析}
583-
先排序,然后左右夹逼,复杂度 $O(n^2)$
584-
需要返回没有duplicate的结果。每次寻找新结果就排除那些可能重复的数字,外层i如果与之前一样则进行下一个,
585-
同理对里层夹逼的两个数也是这样来避免。
586-
\subsubsection{代码}
587-
\begin{Code}
588-
class Solution {
589-
public:
590-
vector<vector<int> > threeSum(vector<int> &num){
591-
sort(num.begin(), num.end());
592-
vector<vector<int> > result;
593-
if(num.size() < 3) return result;
594-
for(int i = 0; i < num.size() - 2; ++i){
595-
if(i && num[i] == num[i - 1]) continue;
596-
int j = i + 1;
597-
int k = num.size() - 1;
598-
while(j < k){
599-
if(num[i] + num[j] + num[k] == 0){
600-
result.push_back({num[i], num[j], num[k]});
601-
++j, --k;
602-
while(num[j] == num[j - 1] && num[k] == num[k + 1] && j < k){
603-
++j, --k;
604-
}
605-
}
606-
else if(num[i] + num[j] + num[k] < 0){
607-
++j;
608-
while(num[j] == num[j - 1] && j < k){
572+
result.push_back({ *i, *j, *k });
609573
++j;
610-
}
611-
}
612-
else{
613-
--k;
614-
while(num[k] == num[k + 1] && j < k){
615574
--k;
575+
while(*j == *(j - 1) && *k == *(k + 1) && j < k) ++j;
616576
}
617577
}
618578
}
579+
return result;
619580
}
620-
return result;
621-
}
622581
};
623582
\end{Code}
624583

C++/leetcode-cpp.pdf

64 Bytes
Binary file not shown.

C++/leetcode-cpp.synctex.gz(busy)

Whitespace-only changes.

0 commit comments

Comments
 (0)