8000 重构 k-sum · samuelcs/leetcode@9753b81 · GitHub
[go: up one dir, main page]

Skip to content

Commit 9753b81

Browse files
committed
重构 k-sum
1 parent 7200400 commit 9753b81

File tree

3 files changed

+158
-138
lines changed

3 files changed

+158
-138
lines changed

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

1.97 KB
Binary file not shown.

C++/chapImplement.tex

Lines changed: 0 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -108,62 +108,6 @@ \subsubsection{相关题目}
108108
\myenddot
109109

110110

111-
\section{Two Sum} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
112-
\label{sec:wordladder}
113-
114-
115-
\subsubsection{描述}
116-
Given an array of integers, find two numbers such that they add up to a specific target number.
117-
118-
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
119-
120-
You may assume that each input would have exactly one solution.
121-
122-
Input: \code{numbers=\{2, 7, 11, 15\}, target=9}
123-
124-
Output: \code{index1=1, index2=2}
125-
126-
127-
\subsubsection{分析}
128-
方法1:暴力,复杂度$O(n^2)$,会超时
129-
130-
方法2:hash。用一个哈希表,存储每个数对应的下标,复杂度$O(n)$
131-
132-
133-
\subsubsection{代码}
134-
\begin{Code}
135-
//LeetCode, Two Sum
136-
// 方法2:hash。用一个哈希表,存储每个数对应的下标
137-
// 时间复杂度O(n),空间复杂度O(n)
138-
class Solution {
139-
public:
140-
vector<int> twoSum(vector<int> &numbers, int target) {
141-
unordered_map<int, int> mapping;
142-
vector<int> result;
143-
for (int i = 0; i < numbers.size(); i++) {
144-
mapping[numbers[i]] = i;
145-
}
146-
for (int i = 0; i < numbers.size(); i++) {
147-
const int gap = target - numbers[i];
148-
if (mapping.find(gap) != mapping.end()) {
149-
result.push_back(i + 1);
150-
result.push_back(mapping[gap] + 1);
151-
break;
152-
}
153-
}
154-
return result;
155-
}
156-
};
157-
\end{Code}
158-
159-
160-
\subsubsection{相关题目}
161-
162-
\begindot
163-
\item
164-
\myenddot
165-
166-
167111
\section{Insert Interval} %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
168112
\label{sec:insert-interval}
169113

0 commit comments

Comments
 (0)
0