提交 5567bdaa 编写于 作者: 每日一练社区's avatar 每日一练社区

add exercises 15

上级 88988463
{
"node_id": "algorithm-e390d7a141d94907930a50469baa0cfa",
"keywords": [
"leetcode",
"最小栈"
],
"children": [],
"export": [
"solution.json"
],
"title": "最小栈"
}
\ No newline at end of file
<p>设计一个支持 <code>push</code><code>pop</code><code>top</code> 操作,并能在常数时间内检索到最小元素的栈。</p>
<ul>
<li><code>push(x)</code> &mdash;&mdash; 将元素 x 推入栈中。</li>
<li><code>pop()</code>&nbsp;&mdash;&mdash; 删除栈顶的元素。</li>
<li><code>top()</code>&nbsp;&mdash;&mdash; 获取栈顶元素。</li>
<li><code>getMin()</code> &mdash;&mdash; 检索栈中的最小元素。</li>
</ul>
<p>&nbsp;</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong>
[&quot;MinStack&quot;,&quot;push&quot;,&quot;push&quot;,&quot;push&quot;,&quot;getMin&quot;,&quot;pop&quot;,&quot;top&quot;,&quot;getMin&quot;]
[[],[-2],[0],[-3],[],[],[],[]]
<strong>输出:</strong>
[null,null,null,null,-3,null,0,-2]
<strong>解释:</strong>
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --&gt; 返回 -3.
minStack.pop();
minStack.top(); --&gt; 返回 0.
minStack.getMin(); --&gt; 返回 -2.
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>pop</code><code>top</code><code>getMin</code> 操作总是在 <strong>非空栈</strong> 上调用。</li>
</ul>
class MinStack
{
private:
stack<int> s1;
stack<int> s2;
public:
void push(int x)
{
s1.push(x);
if (s2.empty() || x <= getMin())
s2.push(x);
}
void pop()
{
//在这里判断一下就是s2最小栈 二个栈中栈顶元素相同最小栈中的元素才会出栈;
if (s1.top() == getMin())
s2.pop();
s1.pop();
}
int top()
{
return s1.top();
}
int getMin()
{
return s2.top();
}
};
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "0f95022f0b7c41659f8912ce7935e2d9"
}
\ No newline at end of file
# 最小栈
<p>设计一个支持 <code>push</code><code>pop</code><code>top</code> 操作,并能在常数时间内检索到最小元素的栈。</p>
<ul>
<li><code>push(x)</code> &mdash;&mdash; 将元素 x 推入栈中。</li>
<li><code>pop()</code>&nbsp;&mdash;&mdash; 删除栈顶的元素。</li>
<li><code>top()</code>&nbsp;&mdash;&mdash; 获取栈顶元素。</li>
<li><code>getMin()</code> &mdash;&mdash; 检索栈中的最小元素。</li>
</ul>
<p>&nbsp;</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong>
[&quot;MinStack&quot;,&quot;push&quot;,&quot;push&quot;,&quot;push&quot;,&quot;getMin&quot;,&quot;pop&quot;,&quot;top&quot;,&quot;getMin&quot;]
[[],[-2],[0],[-3],[],[],[],[]]
<strong>输出:</strong>
[null,null,null,null,-3,null,0,-2]
<strong>解释:</strong>
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --&gt; 返回 -3.
minStack.pop();
minStack.top(); --&gt; 返回 0.
minStack.getMin(); --&gt; 返回 -2.
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>pop</code><code>top</code><code>getMin</code> 操作总是在 <strong>非空栈</strong> 上调用。</li>
</ul>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
```
## 答案
```cpp
其他三个都是错的
```
## 选项
### A
```cpp
class MinStack
{
public:
/** initialize your data structure here. */
private:
stack<long int> s;
stack<long int> mins;
public:
MinStack()
{
while (!s.empty())
{
s.pop();
}
while (!mins.empty())
{
mins.pop();
}
}
void push(int x)
{
if (s.empty())
{
s.push(x);
mins.push(x);
}
else
{
if (mins.top() >= x)
{
s.push(x);
mins.push(x);
}
else
{
mins.push(mins.top());
s.push(x);
}
}
}
void pop()
{
s.pop();
mins.pop();
}
int top()
{
return s.top();
}
int getMin()
{
return mins.top();
}
};
```
### B
```cpp
class MinStack
{
public:
/** initialize your data structure here. */
stack<int> s;
MinStack()
{
}
void push(int x)
{
if (s.empty())
{
s.push(x);
s.push(x);
}
else
{
int temp = s.top();
s.push(x);
if (x < temp)
{
s.push(x);
}
else
{
s.push(temp);
}
}
}
void pop()
{
s.pop();
s.pop();
}
int top()
{
int temp = s.top();
s.pop();
int top = s.top();
s.push(temp);
return top;
}
int getMin()
{
return s.top();
}
};
```
### C
```cpp
class MinStack
{
public:
stack<int> s;
stack<int> min;
/** initialize your data structure here. */
MinStack()
{
}
void push(int x)
{
s.push(x);
if (min.empty() || x <= min.top())
{
min.push(x);
}
}
void pop()
{
if (s.top() == min.top())
min.pop();
s.pop();
}
int top()
{
return s.top();
}
int getMin()
{
return min.top();
}
};
```
{
"node_id": "algorithm-56c34a1192d0451cb982e456a82c5c6d",
"keywords": [
"leetcode",
"基本计算器"
],
"children": [],
"export": [
"solution.json"
],
"title": "基本计算器"
}
\ No newline at end of file
<p>给你一个字符串表达式 <code>s</code> ,请你实现一个基本计算器来计算并返回它的值。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>s = "1 + 1"
<strong>输出:</strong>2
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>s = " 2-1 + 2 "
<strong>输出:</strong>3
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>s = "(1+(4+5+2)-3)+(6+8)"
<strong>输出:</strong>23
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= s.length <= * 10<sup>5</sup></code></li>
<li><code>s</code> 由数字、<code>'+'</code><code>'-'</code><code>'('</code><code>')'</code>、和 <code>' '</code> 组成</li>
<li><code>s</code> 表示一个有效的表达式</li>
</ul>
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "dc5d688388b042fabf28658a12bb1d69"
}
\ No newline at end of file
# 基本计算器
<p>给你一个字符串表达式 <code>s</code> ,请你实现一个基本计算器来计算并返回它的值。</p>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>s = "1 + 1"
<strong>输出:</strong>2
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>s = " 2-1 + 2 "
<strong>输出:</strong>3
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>s = "(1+(4+5+2)-3)+(6+8)"
<strong>输出:</strong>23
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= s.length <= * 10<sup>5</sup></code></li>
<li><code>s</code> 由数字、<code>'+'</code><code>'-'</code><code>'('</code><code>')'</code>、和 <code>' '</code> 组成</li>
<li><code>s</code> 表示一个有效的表达式</li>
</ul>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
int res;
string s1 = "(1+(4+5+2)-3)+(6+8)";
res = sol.calculate(s1);
cout << res;
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int calculate(string s)
{
stack<string> expr, nums, ops;
int cur = 0, len = s.size();
string tmp = "";
while (cur < len)
{
switch (s[cur])
{
case ' ':
break;
case '+':
case '-':
case '(':
if (tmp != "")
{
expr.push(tmp);
tmp = "";
}
expr.push(tmp + s[cur]);
break;
case ')':
{
if (tmp != "")
{
expr.push(tmp);
tmp = "";
}
int caled = calculate(expr);
expr.push(intToStr(caled));
break;
}
default:
tmp += s[cur];
break;
}
++cur;
}
if (tmp != "")
expr.push(tmp);
return calculate(expr);
}
private:
int calculate(stack<string> &s)
{
stack<int> nums;
stack<char> ops;
string top;
while (!s.empty() && (top = s.top()) != "(")
{
if (top == "+" || top == "-")
ops.push(top[0]);
else
nums.push(strToInt(top));
s.pop();
}
if (!s.empty())
s.pop();
int ans = nums.top(), num;
nums.pop();
while (!ops.empty())
{
num = nums.top();
nums.pop();
if (ops.top() == '+')
ans += num;
else
ans -= num;
}
return ans;
}
int strToInt(string s)
{
int ans = 0, len = s.size();
if (len == 0)
return 0;
int symbol = s[0] == '-' ? -1 : 1;
for (int i = s[0] == '+' || s[0] == '-' ? 1 : 0; i < len; ++i)
{
ans *= 10;
ans += s[i] - '0';
}
return ans * symbol;
}
string intToStr(int num)
{
if (num == 0)
return "0";
int symbol = num >= 0 ? 1 : -1;
string s = "";
num *= symbol;
while (num)
{
s = (char)(num % 10 + '0') + s;
num /= 10;
}
if (symbol == -1)
s = "-" + s;
return s;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int calculate(string s)
{
stack<long> conclude;
stack<char> fuhao;
int i = 0, len = s.length();
while (i < len)
{
if (s[i] == ' ')
i++;
else if (s[i] == '(')
{
fuhao.push('(');
i++;
}
else if (s[i] == ')')
{
if (fuhao.top() != '(')
{
long x = conclude.top();
conclude.pop();
long y = conclude.top();
conclude.pop();
if (fuhao.top() == '+')
conclude.push(y + x);
else
conclude.push(y - x);
fuhao.pop();
}
fuhao.pop();
i++;
}
else if (s[i] == '+' || s[i] == '-')
{
if (!fuhao.empty() && fuhao.top() != '(')
{
long x = conclude.top();
conclude.pop();
long y = conclude.top();
conclude.pop();
if (fuhao.top() == '+')
conclude.push(y + x);
else
conclude.push(y - x);
fuhao.pop();
}
fuhao.push(s[i]);
i++;
}
else
{
long x = s[i] - '0';
i++;
while (i < len && s[i] <= '9' && s[i] >= '0')
{
x = x * 10 + (s[i] - '0');
i++;
}
conclude.push(x);
}
}
if (!fuhao.empty())
{
long x = conclude.top();
conclude.pop();
long y = conclude.top();
conclude.pop();
if (fuhao.top() == '+')
conclude.push(y + x);
else
conclude.push(y - x);
fuhao.pop();
}
return conclude.top();
}
};
```
### B
```cpp
class Solution
{
public:
int calculate(string s)
{
static const int STATE_BEGIN = 0;
static const int NUMBER_STATE = 1;
static const int OPERATION_STATE = 2;
long number = 0;
int STATE = STATE_BEGIN;
int computer_flag = 0;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == ' ')
{
continue;
}
switch (STATE)
{
case STATE_BEGIN:
if (s[i] >= '0' && s[i] <= '9')
{
STATE = NUMBER_STATE;
}
else
{
STATE = OPERATION_STATE;
}
i--;
break;
case NUMBER_STATE:
if (s[i] >= '0' && s[i] <= '9')
{
number = number * 10 + s[i] - '0';
}
else
{
number_stack.push(number);
if (computer_flag == 1)
{
computer(number_stack, operation_stack);
}
number = 0;
i--;
STATE = OPERATION_STATE;
}
break;
case OPERATION_STATE:
if (s[i] == '+' || s[i] == '-')
{
operation_stack.push(s[i]);
computer_flag = 1;
}
else if (s[i] == '(')
{
computer_flag = 0;
}
else if (s[i] >= '0' && s[i] <= '9')
{
STATE = NUMBER_STATE;
i--;
}
else if (s[i] == ')')
{
computer(number_stack, operation_stack);
}
break;
}
}
if (number != 0)
{
number_stack.push(number);
computer(number_stack, operation_stack);
}
if (number == 0 && number_stack.empty())
{
return 0;
}
return number_stack.top();
}
void computer(stack<long> &number_stack, stack<char> &operation_stack)
{
if (number_stack.size() < 2)
{
return;
}
int num2 = number_stack.top();
number_stack.pop();
int num1 = number_stack.top();
number_stack.pop();
if (operation_stack.top() == '+')
{
number_stack.push(num1 + num2);
}
else if (operation_stack.top() == '-')
{
number_stack.push(num1 - num2);
}
operation_stack.pop();
}
private:
stack<long> number_stack;
stack<char> operation_stack;
};
```
### C
```cpp
class Solution
{
public:
void sum(vector<string> &stk)
{
vector<string> temp;
while (!stk.empty() && stk.back() != "(")
{
temp.push_back(stk.back());
stk.pop_back();
}
if (!stk.empty() && stk.back() == "(")
stk.pop_back();
if (temp.back() != "-")
temp.emplace_back("+");
reverse(temp.begin(), temp.end());
int ret = 0;
int n = temp.size();
for (int i = 0; i < n - 1; i += 2)
{
int num = stoi(temp[i + 1]);
if (temp[i] == "-")
num *= (-1);
ret += num;
}
stk.push_back(to_string(ret));
}
int calculate(string s)
{
vector<string> stk;
int n = s.size();
int ret = 0;
string temp;
for (int i = 0; i < n; ++i)
{
if (isdigit(s[i]))
{
temp += s[i];
}
else if (s[i] == '+' || s[i] == '-')
{
if (!temp.empty())
{
stk.push_back(temp);
temp.clear();
}
temp += s[i];
stk.push_back(temp);
temp.clear();
}
else if (s[i] == '(')
{
temp += s[i];
stk.push_back(temp);
temp.clear();
}
else if (s[i] == ')')
{
stk.push_back(temp);
temp.clear();
sum(stk);
}
}
if (!temp.empty())
stk.push_back(temp);
sum(stk);
if (stk.size() == 1)
ret = stoi(stk[0]);
return ret;
}
};
```
{
"node_id": "algorithm-c75a176a776a4b2d87cf2be7102b49b7",
"keywords": [
"leetcode",
"基本计算器 II"
],
"children": [],
"export": [
"solution.json"
],
"title": "基本计算器 II"
}
\ No newline at end of file
<p>给你一个字符串表达式 <code>s</code> ,请你实现一个基本计算器来计算并返回它的值。</p>
<p>整数除法仅保留整数部分。</p>
<div class="original__bRMd">
<div>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>s = "3+2*2"
<strong>输出:</strong>7
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>s = " 3/2 "
<strong>输出:</strong>1
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>s = " 3+5 / 2 "
<strong>输出:</strong>5
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> 由整数和算符 <code>('+', '-', '*', '/')</code> 组成,中间由一些空格隔开</li>
<li><code>s</code> 表示一个 <strong>有效表达式</strong></li>
<li>表达式中的所有整数都是非负整数,且在范围 <code>[0, 2<sup>31</sup> - 1]</code></li>
<li>题目数据保证答案是一个 <strong>32-bit 整数</strong></li>
</ul>
</div>
</div>
class Solution
{
public:
int calculate(string s)
{
vector<int> stk;
char preSign = '+';
int num = 0;
int n = s.length();
for (int i = 0; i < n; ++i)
{
if (isdigit(s[i]))
{
num = num * 10 + int(s[i] - '0');
}
if (!isdigit(s[i]) && s[i] != ' ' || i == n - 1)
{
switch (preSign)
{
case '+':
stk.push_back(num);
break;
case '-':
stk.push_back(-num);
break;
case '*':
stk.back() *= num;
break;
default:
stk.back() /= num;
}
preSign = s[i];
num = 0;
}
}
return accumulate(stk.begin(), stk.end(), 0);
}
};
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "c33c41a793664202bdac71c5e0266968"
}
\ No newline at end of file
# 基本计算器 II
<p>给你一个字符串表达式 <code>s</code> ,请你实现一个基本计算器来计算并返回它的值。</p>
<p>整数除法仅保留整数部分。</p>
<div class="original__bRMd">
<div>
<p> </p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>s = "3+2*2"
<strong>输出:</strong>7
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>s = " 3/2 "
<strong>输出:</strong>1
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>s = " 3+5 / 2 "
<strong>输出:</strong>5
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= s.length <= 3 * 10<sup>5</sup></code></li>
<li><code>s</code> 由整数和算符 <code>('+', '-', '*', '/')</code> 组成,中间由一些空格隔开</li>
<li><code>s</code> 表示一个 <strong>有效表达式</strong></li>
<li>表达式中的所有整数都是非负整数,且在范围 <code>[0, 2<sup>31</sup> - 1]</code></li>
<li>题目数据保证答案是一个 <strong>32-bit 整数</strong></li>
</ul>
</div>
</div>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
int res;
string s1 = "3+2*2";
res = sol.calculate(s1);
cout << res;
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int calculate(string s)
{
int res = 0;
stack<int> my_stack{};
vector<char> my_vec{};
for (auto x : s)
{
if (x != ' ')
my_vec.push_back(x);
}
int start = 0;
int end = 0;
int tmp = 0;
while (start != my_vec.size())
{
tmp = 0;
for (int i = start; i < my_vec.size(); i++)
{
if (my_vec[i] >= '0')
{
if (i == 0)
{
tmp = my_vec[i] - '0';
}
else if (my_vec[i - 1] == '+' || my_vec[i - 1] == '*' || my_vec[i - 1] == '/')
tmp = my_vec[i] - '0';
else if (my_vec[i - 1] == '-')
tmp = -1 * (my_vec[i] - '0');
else if (my_vec[i - 1] >= '0')
{
if (tmp >= 0)
tmp = tmp * 10 + (my_vec[i] - '0');
else
tmp = tmp * 10 - (my_vec[i] - '0');
}
if (i == my_vec.size() - 1)
end = i;
}
else
{
end = i;
break;
}
}
if (start == 0)
my_stack.push(tmp);
else
{
if (my_vec[start - 1] == '+' || my_vec[start - 1] == '-')
my_stack.push(tmp);
else if (my_vec[start - 1] == '*')
my_stack.top() = my_stack.top() * tmp;
else if (my_vec[start - 1] == '/')
my_stack.top() = my_stack.top() / tmp;
}
start = end + 1;
}
while (!my_stack.empty())
{
res = my_stack.top();
my_stack.pop();
}
return res;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int calculate(string s)
{
int ans = 0;
int n = s.size();
char ope = '+';
stack<int> temp;
int d = 0;
int A;
for (int i = 0; i < n; i++)
{
if (s[i] - '0' >= 0 && s[i] - '0' <= 9)
{
d = d * 10 + (s[i] - '0');
}
if ((s[i] < '0' && s[i] != ' ') || i == n - 1)
{
if (ope == '+')
{
temp.push(d);
}
if (ope == '-')
{
temp.push(-d);
}
if (ope == '*')
{
A = temp.top() * d;
temp.pop();
temp.push(A);
}
if (ope == '/')
{
A = temp.top() / d;
temp.pop();
temp.push(A);
}
ope = s[i];
d = 0;
}
}
while (!temp.empty())
{
ans += temp.top();
temp.pop();
}
return ans;
}
};
```
### B
```cpp
class Solution
{
public:
int calculate(string s)
{
stack<char> fuhao;
stack<long> conclude;
int i = 0, len = s.length();
while (i < len)
{
if (s[i] == ' ')
i++;
else if (s[i] >= '0' && s[i] <= '9')
{
long x = s[i] - '0';
i++;
while (i < len && s[i] >= '0' && s[i] <= '9')
{
x = x * 10 + s[i] - '0';
i++;
}
conclude.push(x);
}
else
{
while (!fuhao.empty() && (fuhao.top() == '*' || fuhao.top() == '/' || s[i] == '+' || s[i] == '-'))
{
long x = conclude.top();
conclude.pop();
long y = conclude.top();
conclude.pop();
if (fuhao.top() == '+')
conclude.push(y + x);
else if (fuhao.top() == '-')
conclude.push(y - x);
else if (fuhao.top() == '*')
conclude.push(y * x);
else
conclude.push(y / x);
fuhao.pop();
}
fuhao.push(s[i]);
i++;
}
}
while (!fuhao.empty())
{
long x = conclude.top();
conclude.pop();
long y = conclude.top();
conclude.pop();
if (fuhao.top() == '+')
conclude.push(y + x);
else if (fuhao.top() == '-')
conclude.push(y - x);
else if (fuhao.top() == '*')
conclude.push(y * x);
else
conclude.push(y / x);
fuhao.pop();
}
return conclude.top();
}
};
```
### C
```cpp
class Solution
{
public:
int calculate(string s)
{
vector<int> stk;
char preSign = '+';
int num = 0;
int n = s.length();
for (int i = 0; i < n; ++i)
{
if (isdigit(s[i]))
{
num = num * 10 + int(s[i] - '0');
}
if (!isdigit(s[i]) && s[i] != ' ' || i == n - 1)
{
switch (preSign)
{
case '+':
stk.push_back(num);
break;
case '-':
stk.push_back(-num);
break;
case '*':
stk.back() *= num;
break;
default:
stk.back() /= num;
}
preSign = s[i];
num = 0;
}
}
return accumulate(stk.begin(), stk.end(), 0);
}
};
```
{
"node_id": "algorithm-e7fb5d6455fe490dbffe4b5cac8a5b95",
"keywords": [
"leetcode",
"最大间距"
],
"children": [],
"export": [
"solution.json"
],
"title": "最大间距"
}
\ No newline at end of file
<p>给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。</p>
<p>如果数组元素个数小于 2,则返回 0。</p>
<p><strong>示例&nbsp;1:</strong></p>
<pre><strong>输入:</strong> [3,6,9,1]
<strong>输出:</strong> 3
<strong>解释:</strong> 排序后的数组是 [1,3,6,9]<strong><em>, </em></strong>其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。</pre>
<p><strong>示例&nbsp;2:</strong></p>
<pre><strong>输入:</strong> [10]
<strong>输出:</strong> 0
<strong>解释:</strong> 数组元素个数小于 2,因此返回 0。</pre>
<p><strong>说明:</strong></p>
<ul>
<li>你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。</li>
<li>请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。</li>
</ul>
class Solution
{
public:
int maximumGap(vector<int> &nums)
{
if (nums.size() < 2)
return 0;
sort(nums.begin(), nums.end());
int max_difference = 0;
for (int i = 0; i < nums.size() - 1; i++)
{
if (nums[i + 1] - nums[i] > max_difference)
max_difference = nums[i + 1] - nums[i];
}
return max_difference;
}
};
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "64be815b65e6441b99ceb749752f8054"
}
\ No newline at end of file
# 最大间距
<p>给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。</p>
<p>如果数组元素个数小于 2,则返回 0。</p>
<p><strong>示例&nbsp;1:</strong></p>
<pre><strong>输入:</strong> [3,6,9,1]
<strong>输出:</strong> 3
<strong>解释:</strong> 排序后的数组是 [1,3,6,9]<strong><em>, </em></strong>其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。</pre>
<p><strong>示例&nbsp;2:</strong></p>
<pre><strong>输入:</strong> [10]
<strong>输出:</strong> 0
<strong>解释:</strong> 数组元素个数小于 2,因此返回 0。</pre>
<p><strong>说明:</strong></p>
<ul>
<li>你可以假设数组中所有元素都是非负整数,且数值在 32 位有符号整数范围内。</li>
<li>请尝试在线性时间复杂度和空间复杂度的条件下解决此问题。</li>
</ul>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
int res;
vector<int> nums = {3, 6, 9, 1};
res = sol.maximumGap(nums);
cout << res;
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int maximumGap(vector<int> &nums)
{
int l = 0, r = nums.size() - 1;
while (l < r)
{
int mid = (l + r) / 2;
if (nums[mid] < nums[mid + 1])
l = mid + 1;
else
r = mid;
}
return r;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int maximumGap(vector<int> &nums)
{
if (nums.size() < 2)
return 0;
if (nums.size() == 2)
return abs(nums[1] - nums[0]);
int maxn = 0;
int minn = INT_MAX;
for (int i = 0; i < nums.size(); i++)
maxn = max(maxn, nums[i]);
for (int i = 0; i < nums.size(); i++)
minn = min(minn, nums[i]);
if (maxn == minn)
return 0;
int size = (maxn - minn) / nums.size();
if (size < 1)
size = 1;
int num = (maxn - minn) / size + 1;
vector<int> nummax(num, 0);
vector<int> nummin(num, maxn);
nummin[0] = minn;
nummax[0] = minn;
nummax[num - 1] = maxn;
nummin[num - 1] = maxn;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == maxn || nums[i] == minn)
continue;
int qnum = (nums[i] - minn) / size;
nummax[qnum] = max(nummax[qnum], nums[i]);
nummin[qnum] = min(nummin[qnum], nums[i]);
}
for (int i = 0; i < nummin.size(); i++)
{
if (nummax[i] == 0 && nummin[i] == maxn)
{
nummax.erase(nummax.begin() + i);
nummin.erase(nummin.begin() + i);
i--;
}
}
int res = 0;
for (int i = 1; i < nummax.size(); i++)
{
res = max(res, nummin[i] - nummax[i - 1]);
}
return res;
}
};
```
### B
```cpp
class Solution
{
public:
int maximumGap(vector<int> &nums)
{
if (nums.empty())
return 0;
int mx = INT_MIN, mn = INT_MAX, n = nums.size();
for (int a : nums)
{
mx = max(a, mx);
mn = min(a, mn);
}
int size = (mx - mn) / n + 1;
int bucket_nums = (mx - mn) / size + 1;
vector<int> bucket_min(bucket_nums, INT_MAX);
vector<int> bucket_max(bucket_nums, INT_MIN);
set<int> s;
for (int a : nums)
{
int indx = (a - mn) / size;
bucket_max[indx] = max(bucket_max[indx], a);
bucket_min[indx] = min(bucket_min[indx], a);
s.insert(indx);
}
int pre = 0, ans = 0;
for (int i = 1; i < bucket_nums; ++i)
{
if (!s.count(i))
continue;
int t = bucket_min[i] - bucket_max[pre];
ans = max(ans, t);
pre = i;
}
return ans;
}
};
```
### C
```cpp
class Solution
{
public:
static bool cmp(const int &a, const int &b)
{
return a < b;
}
int maximumGap(vector<int> &nums)
{
if (nums.size() <= 1)
return 0;
sort(nums.begin(), nums.end(), cmp);
int maxgap = 0;
for (int i = 1; i < nums.size(); i++)
{
maxgap = max(maxgap, nums[i] - nums[i - 1]);
}
return maxgap;
}
};
```
{
"node_id": "algorithm-4b5f859d4b83448e81381353bc1eba4c",
"keywords": [
"leetcode",
"计算右侧小于当前元素的个数"
],
"children": [],
"export": [
"solution.json"
],
"title": "计算右侧小于当前元素的个数"
}
\ No newline at end of file
<p>给你`一个整数数组 <code>nums</code><em> </em>,按要求返回一个新数组&nbsp;<code>counts</code><em> </em>。数组 <code>counts</code> 有该性质: <code>counts[i]</code> 的值是&nbsp; <code>nums[i]</code> 右侧小于&nbsp;<code>nums[i]</code> 的元素的数量。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>nums = [5,2,6,1]
<strong>输出:</strong><code>[2,1,1,0]
<strong>解释:</strong></code>
5 的右侧有 <strong>2 </strong>个更小的元素 (2 和 1)
2 的右侧仅有 <strong>1 </strong>个更小的元素 (1)
6 的右侧有 <strong>1 </strong>个更小的元素 (1)
1 的右侧有 <strong>0 </strong>个更小的元素
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>nums = [-1]
<strong>输出:</strong>[0]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>nums = [-1,-1]
<strong>输出:</strong>[0,0]
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "3287ad707ee3486098dea0dd251ae5ad"
}
\ No newline at end of file
# 计算右侧小于当前元素的个数
<p>给你`一个整数数组 <code>nums</code><em> </em>,按要求返回一个新数组&nbsp;<code>counts</code><em> </em>。数组 <code>counts</code> 有该性质: <code>counts[i]</code> 的值是&nbsp; <code>nums[i]</code> 右侧小于&nbsp;<code>nums[i]</code> 的元素的数量。</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong>nums = [5,2,6,1]
<strong>输出:</strong><code>[2,1,1,0]
<strong>解释:</strong></code>
5 的右侧有 <strong>2 </strong>个更小的元素 (2 和 1)
2 的右侧仅有 <strong>1 </strong>个更小的元素 (1)
6 的右侧有 <strong>1 </strong>个更小的元素 (1)
1 的右侧有 <strong>0 </strong>个更小的元素
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>nums = [-1]
<strong>输出:</strong>[0]
</pre>
<p><strong>示例 3:</strong></p>
<pre>
<strong>输入:</strong>nums = [-1,-1]
<strong>输出:</strong>[0,0]
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
vector<int> res;
vector<int> nums = {5, 2, 6, 1};
res = sol.countSmaller(nums);
for (auto i : res)
cout << i << " ";
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int lowbit(int x)
{
return (int)x & (-1 * x);
}
int getSum(int x, vector<int> &c)
{
int sum = 0;
for (int i = x; i > 0; i -= lowbit(i))
{
sum += c[i];
}
return sum;
}
void update(vector<int> &c, int x, int v)
{
for (int i = x; i < c.size(); i += lowbit(i))
{
c[i] += v;
}
}
vector<int> countSmaller(vector<int> &nums)
{
vector<int> count;
set<int> ss;
for (auto t : nums)
{
ss.insert(t);
}
unordered_map<int, int> m;
int n = ss.size();
auto it = ss.begin();
for (int i = 1; i <= n; i++)
{
it++;
m[*it] = i;
}
vector<int> sum(n + 1, 0);
for (auto it = nums.rbegin(); it != nums.rend(); it++)
{
int res = 0;
int idx = m[*it];
if (idx > 1)
{
res = getSum(idx - 1, sum);
}
update(sum, m[*it], 1);
count.push_back(res);
}
reverse(count.begin(), count.end());
return count;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector<int> countSmaller(vector<int> &nums)
{
vector<int> res(nums.size(), 0);
vector<int> indexs(nums.size(), 0);
for (int i = 0; i < indexs.size(); i++)
{
indexs[i] = i;
}
vector<int> tempindexs(indexs.size(), 0);
mergeSort(nums, indexs, tempindexs, res, 0, nums.size() - 1);
return res;
}
void mergeSort(vector<int> &nums, vector<int> &indexs, vector<int> &tempindexs, vector<int> &res, int left, int right)
{
if (left >= right)
return;
int mid = left + (right - left) / 2;
mergeSort(nums, indexs, tempindexs, res, left, mid);
mergeSort(nums, indexs, tempindexs, res, mid + 1, right);
int i = left;
int j = mid + 1;
int t = 0;
while (i <= mid && j <= right)
{
if (nums[indexs[i]] > nums[indexs[j]])
{
for (int k = i; k <= mid; k++)
{
res[indexs[k]]++;
}
tempindexs[t++] = indexs[j++];
}
else
{
tempindexs[t++] = indexs[i++];
}
}
while (i <= mid)
{
tempindexs[t++] = indexs[i++];
}
while (j <= right)
{
tempindexs[t++] = indexs[j++];
}
t = 0;
while (left <= right)
{
indexs[left++] = tempindexs[t++];
}
}
};
```
### B
```cpp
struct BSTNode
{
int val;
int count;
BSTNode *left;
BSTNode *right;
BSTNode(int x) : val(x), left(NULL), right(NULL), count(0) {}
};
void BST_insert(BSTNode *node, BSTNode *insert_node, int &count_small)
{
if (node->val >= insert_node->val)
{
node->count++;
if (node->left)
BST_insert(node->left, insert_node, count_small);
else
node->left = insert_node;
}
else
{
count_small += node->count + 1;
if (node->right)
BST_insert(node->right, insert_node, count_small);
else
node->right = insert_node;
}
}
class Solution
{
public:
vector<int> countSmaller(vector<int> &nums)
{
int n = nums.size();
if (!n)
return {};
vector<int> count;
count.push_back(0);
BSTNode *node = new BSTNode(nums[n - 1]);
int count_small;
for (int i = 1; i < n; ++i)
{
count_small = 0;
BST_insert(node, new BSTNode(nums[n - i - 1]), count_small);
count.push_back(count_small);
}
delete node;
reverse(count.begin(), count.end());
return count;
}
};
```
### C
```cpp
class Solution
{
public:
vector<int> help;
vector<int> countSmaller(vector<int> &nums)
{
int n = nums.size();
if (n == 0)
return vector<int>();
vector<int> res(n, 0);
for (int i = n - 1; i >= 0; --i)
{
auto it = lower_bound(help.begin(), help.end(), nums[i]);
res[i] = it - help.begin();
help.insert(it, nums[i]);
}
return res;
}
};
```
{
"node_id": "algorithm-56f49e9431934f4ab2e3b09586675d3c",
"keywords": [
"leetcode",
"区间和的个数"
],
"children": [],
"export": [
"solution.json"
],
"title": "区间和的个数"
}
\ No newline at end of file
<p>给你一个整数数组 <code>nums</code> 以及两个整数 <code>lower</code><code>upper</code> 。求数组中,值位于范围 <code>[lower, upper]</code> (包含 <code>lower</code> 和 <code>upper</code>)之内的 <strong>区间和的个数</strong></p>
<p><strong>区间和</strong> <code>S(i, j)</code> 表示在 <code>nums</code> 中,位置从 <code>i</code> 到 <code>j</code> 的元素之和,包含 <code>i</code> 和 <code>j</code> (<code>i</code><code>j</code>)。</p>
<p> </p>
<strong>示例 1:</strong>
<pre>
<strong>输入:</strong>nums = [-2,5,-1], lower = -2, upper = 2
<strong>输出:</strong>3
<strong>解释:</strong>存在三个区间:[0,0]、[2,2] 和 [0,2] ,对应的区间和分别是:-2 、-1 、2 。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>nums = [0], lower = 0, upper = 0
<strong>输出:</strong>1
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li><code>-10<sup>5</sup> <= lower <= upper <= 10<sup>5</sup></code></li>
<li>题目数据保证答案是一个 <strong>32 位</strong> 的整数</li>
</ul>
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "8c88978f29ec428ba4162fb079a65a5d"
}
\ No newline at end of file
# 区间和的个数
<p>给你一个整数数组 <code>nums</code> 以及两个整数 <code>lower</code><code>upper</code> 。求数组中,值位于范围 <code>[lower, upper]</code> (包含 <code>lower</code> 和 <code>upper</code>)之内的 <strong>区间和的个数</strong></p>
<p><strong>区间和</strong> <code>S(i, j)</code> 表示在 <code>nums</code> 中,位置从 <code>i</code> 到 <code>j</code> 的元素之和,包含 <code>i</code> 和 <code>j</code> (<code>i</code><code>j</code>)。</p>
<p> </p>
<strong>示例 1:</strong>
<pre>
<strong>输入:</strong>nums = [-2,5,-1], lower = -2, upper = 2
<strong>输出:</strong>3
<strong>解释:</strong>存在三个区间:[0,0]、[2,2] 和 [0,2] ,对应的区间和分别是:-2 、-1 、2 。
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong>nums = [0], lower = 0, upper = 0
<strong>输出:</strong>1
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
<li><code>-10<sup>5</sup> <= lower <= upper <= 10<sup>5</sup></code></li>
<li>题目数据保证答案是一个 <strong>32 位</strong> 的整数</li>
</ul>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
int res;
vector<int> nums = {-2, 5, -1};
int lower = -2;
int upper = 2;
res = sol.countRangeSum(nums, lower, upper);
cout << res;
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int lower, upper, res;
long tmp[10000];
void merge(vector<long> &a, int l, int mid, int r)
{
int i = l, j = mid + 1, k = 0;
while (i <= mid && j <= r)
{
if (a[i] <= a[j])
tmp[k++] = a[i++];
else
tmp[k++] = a[j++];
}
while (i <= mid)
tmp[k++] = a[i++];
while (j <= r)
tmp[k++] = a[j++];
copy(tmp, tmp + k, a.begin() + l);
}
void merge_sort(vector<long> &a, int l, int r)
{
if (l >= r)
return;
int mid = l + r - l / 2;
merge_sort(a, l, mid);
merge_sort(a, mid + 1, r);
int k = mid + 1, j = k;
for (int i = l; i <= mid; ++i)
{
while (k <= r && a[k] - a[i] < lower)
++k;
while (j <= r && a[j] - a[i] <= upper)
++j;
res += j - k;
}
if (a[mid] <= a[mid + 1])
return;
merge(a, l, mid, r);
}
int countRangeSum(vector<int> &nums, int lower, int upper)
{
this->lower = lower;
this->upper = upper;
int n = nums.size();
vector<long> presum(n + 1, 0);
for (int i = 0; i < n; ++i)
presum[i] = presum[i] + nums[i];
merge_sort(presum, 0, n);
return res;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int countRangeSum(vector<int> &nums, int lower, int upper)
{
int n = nums.size();
long presum = 0;
multiset<long> S;
S.insert(0);
int ret = 0;
for (int i = 0; i < n; i++)
{
presum += nums[i];
ret += distance(S.lower_bound(presum - upper), S.upper_bound(presum - lower));
S.insert(presum);
}
return ret;
}
};
```
### B
```cpp
class Solution
{
public:
int countRangeSum(vector<int> &nums, int lower, int upper)
{
int n = nums.size();
long presum = 0;
vector<long> S(n + 1, 0);
int ret = 0;
for (int i = 1; i <= n; i++)
{
presum += nums[i - 1];
for (int j = 1; j <= i; j++)
{
if (lower <= presum - S[j - 1] && presum - S[j - 1] <= upper)
ret++;
}
S[i] = presum;
}
return ret;
}
};
```
### C
```cpp
class Solution
{
public:
int countRangeSum(vector<int> &nums, int lower, int upper)
{
int count = 0;
for (int i = 0; i < nums.size(); ++i)
{
if (nums[i] <= upper && nums[i] >= lower)
++count;
long sum = nums[i];
for (int j = i + 1; j < nums.size(); ++j)
{
sum += nums[j];
if (sum <= upper && sum >= lower)
++count;
}
}
return count;
}
};
```
{
"node_id": "algorithm-3a4e0f87183b4a27b08de2624304ca54",
"keywords": [
"leetcode",
"翻转对"
],
"children": [],
"export": [
"solution.json"
],
"title": "翻转对"
}
\ No newline at end of file
<p>给定一个数组&nbsp;<code>nums</code>&nbsp;,如果&nbsp;<code>i &lt; j</code>&nbsp;&nbsp;<code>nums[i] &gt; 2*nums[j]</code>&nbsp;我们就将&nbsp;<code>(i, j)</code>&nbsp;称作一个<strong><em>重要翻转对</em></strong></p>
<p>你需要返回给定数组中的重要翻转对的数量。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入</strong>: [1,3,2,3,1]
<strong>输出</strong>: 2
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入</strong>: [2,4,3,5,1]
<strong>输出</strong>: 3
</pre>
<p><strong>注意:</strong></p>
<ol>
<li>给定数组的长度不会超过<code>50000</code></li>
<li>输入数组中的所有数字都在32位整数的表示范围内。</li>
</ol>
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "bea54ba3bb72429a83f0b240e09f37eb"
}
\ No newline at end of file
# 翻转对
<p>给定一个数组&nbsp;<code>nums</code>&nbsp;,如果&nbsp;<code>i &lt; j</code>&nbsp;&nbsp;<code>nums[i] &gt; 2*nums[j]</code>&nbsp;我们就将&nbsp;<code>(i, j)</code>&nbsp;称作一个<strong><em>重要翻转对</em></strong></p>
<p>你需要返回给定数组中的重要翻转对的数量。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入</strong>: [1,3,2,3,1]
<strong>输出</strong>: 2
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入</strong>: [2,4,3,5,1]
<strong>输出</strong>: 3
</pre>
<p><strong>注意:</strong></p>
<ol>
<li>给定数组的长度不会超过<code>50000</code></li>
<li>输入数组中的所有数字都在32位整数的表示范围内。</li>
</ol>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
int res;
vector<int> nums = {1, 3, 2, 3, 1};
res = sol.reversePairs(nums);
cout << res;
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int lowbit(int x)
{
return (int)x & x;
}
int getSum(int x, vector<int> &c)
{
int sum = 0;
for (int i = x; i > 0; i -= lowbit(i))
{
sum += c[i];
}
return sum;
}
void update(vector<int> &c, int x, int v)
{
for (int i = x; i < c.size(); i += lowbit(i))
{
c[i] += v;
}
}
int reversePairs(vector<int> &nums)
{
int maxN = (INT_MAX) / 2, minN = (INT_MIN) / 2;
set<int> ss;
for (auto t : nums)
{
ss.insert(t);
if (t <= maxN && t >= minN)
ss.insert(t * 2);
}
unordered_map<int, int> m;
int n = ss.size();
auto it = ss.begin();
for (int i = 1; i <= n; i++)
{
m[*it] = i;
it++;
}
vector<int> sum(n + 1, 0);
int res = 0;
for (auto t : nums)
{
if (t < minN)
res += getSum(n, sum);
else if (t < maxN)
{
int idx = m[2 * t];
res += (getSum(n, sum) - getSum(idx, sum));
}
update(sum, m[t], 1);
}
return res;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int cnt = 0;
vector<int> tmp;
void merge(vector<int> &nums, int beg, int mid, int end)
{
int i = beg, j = mid + 1;
int k = 0;
while (i <= mid && j <= end)
{
if (nums[i] <= nums[j])
tmp[k++] = nums[i++];
else
tmp[k++] = nums[j++];
}
while (i <= mid)
tmp[k++] = nums[i++];
while (j <= end)
tmp[k++] = nums[j++];
copy(tmp.begin(), tmp.begin() + k, nums.begin() + beg);
}
void merge_sort(vector<int> &nums, int beg, int end)
{
if (beg >= end)
return;
int mid = beg + (end - beg) / 2;
merge_sort(nums, beg, mid);
merge_sort(nums, mid + 1, end);
int i = beg, j = mid + 1;
while (j <= end)
{
while (i <= mid && long(nums[i]) <= 2 * long(nums[j]))
++i;
cnt += mid - i + 1;
++j;
}
if (nums[mid] <= nums[mid + 1])
return;
merge(nums, beg, mid, end);
}
int reversePairs(vector<int> &nums)
{
int n = nums.size();
tmp = vector<int>(n);
merge_sort(nums, 0, n - 1);
return cnt;
}
};
```
### B
```cpp
class Solution
{
public:
int mergeSort(vector<int> &nums, int l, int r)
{
if (l >= r)
return 0;
int res = 0, mid = (l + r) / 2;
res += mergeSort(nums, l, mid);
res += mergeSort(nums, mid + 1, r);
int tl = l, tm = mid, tr = mid + 1;
while (tl <= mid && tr <= r)
{
if ((long)nums[tl] > 2 * (long)nums[tr])
{
res += mid - tl + 1;
++tr;
}
else
{
++tl;
}
}
vector<int> tmp(r - l + 1);
int i = l, j = mid + 1, k = 0;
while (i <= mid && j <= r)
{
if (nums[i] <= nums[j])
{
tmp[k++] = nums[i++];
}
else
tmp[k++] = nums[j++];
}
while (i <= mid)
tmp[k++] = nums[i++];
while (j <= r)
tmp[k++] = nums[j++];
for (int i = l; i <= r; i++)
{
nums[i] = tmp[i - l];
}
return res;
}
int reversePairs(vector<int> &nums)
{
return mergeSort(nums, 0, nums.size() - 1);
}
};
```
### C
```cpp
class Solution
{
public:
int cnt = 0;
int reversePairs(vector<int> &nums)
{
int n = nums.size();
for (int i = 0; i < n - 1; ++i)
{
for (int j = i + 1; j < n; ++j)
{
if (long(nums[i]) > 2 * long(nums[j]))
++cnt;
}
}
return cnt;
}
};
```
{
"node_id": "algorithm-1b8fb429d0f242cb991e78bb19cfda1f",
"keywords": [
"leetcode",
"排序数组"
],
"children": [],
"export": [
"solution.json"
],
"title": "排序数组"
}
\ No newline at end of file
<p>给你一个整数数组&nbsp;<code>nums</code>,请你将该数组升序排列。</p>
<p>&nbsp;</p>
<ol>
</ol>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong>nums = [5,2,3,1]
<strong>输出:</strong>[1,2,3,5]
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong>nums = [5,1,1,2,0,0]
<strong>输出:</strong>[0,0,1,1,2,5]
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ol>
<li><code>1 &lt;= nums.length &lt;= 50000</code></li>
<li><code>-50000 &lt;= nums[i] &lt;= 50000</code></li>
</ol>
# 排序数组
<p>给你一个整数数组&nbsp;<code>nums</code>,请你将该数组升序排列。</p>
<p>&nbsp;</p>
<ol>
</ol>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong>nums = [5,2,3,1]
<strong>输出:</strong>[1,2,3,5]
</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong>nums = [5,1,1,2,0,0]
<strong>输出:</strong>[0,0,1,1,2,5]
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ol>
<li><code>1 &lt;= nums.length &lt;= 50000</code></li>
<li><code>-50000 &lt;= nums[i] &lt;= 50000</code></li>
</ol>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
vector<int> res;
vector<int> nums = {5, 1, 1, 2, 0, 0};
res = sol.sortArray(nums);
for (auto i : res)
cout << i << " ";
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
void make_max_heap(vector<int> &nums, int len)
{
for (int i = (len / 2); i >= 0; --i)
max_heap_fixed(nums, i, len);
}
void max_heap_fixed(vector<int> &nums, int cur_idx, int len)
{
int lchild = (cur_idx << 1) + 1, rchild = (cur_idx << 1) + 2;
while (lchild < len)
{
int large = cur_idx;
if (lchild <= len && nums[lchild] > nums[cur_idx])
{
large = lchild;
}
if (rchild <= len && nums[rchild] > nums[large])
{
large = rchild;
}
if (large != cur_idx)
{
swap(nums[cur_idx], nums[large]);
cur_idx = large;
lchild = cur_idx << 1;
rchild = cur_idx << 2;
}
else
break;
}
}
vector<int> sortArray(vector<int> &nums)
{
int length = nums.size() - 1;
make_max_heap(nums, length);
for (int i = length; i > 0; --i)
{
swap(nums[0], nums[i]);
max_heap_fixed(nums, 0, i - 1);
}
return nums;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector<int> sortArray(vector<int> &nums)
{
if (nums.size() == 1)
return nums;
for (int i = 1; i < nums.size(); ++i)
{
int preIdx = i - 1;
int curVal = nums[i];
while (preIdx >= 0 && curVal > nums[preIdx])
{
nums[preIdx + 1] = nums[preIdx];
preIdx--;
}
nums[preIdx + 1] = curVal;
}
reverse(nums.begin(), nums.end());
return nums;
}
};
```
### B
```cpp
class Solution
{
public:
void swap(int &a, int &b)
{
int tmp = a;
a = b;
b = tmp;
}
vector<int> sortArray(vector<int> &nums)
{
if (nums.size() == 1)
return nums;
for (int i = 0; i < nums.size() - 1; ++i)
{
int minIndex = i;
for (int j = i + 1; j < nums.size(); ++j)
{
if (nums[i] > nums[j])
{
minIndex = j;
}
}
if (minIndex != i)
{
swap(nums[minIndex], nums[i]);
}
}
return nums;
}
};
```
### C
```cpp
class Solution
{
public:
vector<int> sortArray(vector<int> &nums)
{
if (nums.size() == 1)
return nums;
int tmp;
bool sorted = true;
for (int i = 0; i < nums.size() - 1; ++i)
{
for (int j = nums.size() - 1; j > i; --j)
{
if (nums[j - 1] > nums[j])
{
tmp = nums[j - 1];
nums[j - 1] = nums[j];
nums[j] = tmp;
sorted = false;
}
}
if (sorted)
return nums;
}
return nums;
}
};
```
### D
```cpp
class Solution
{
public:
vector<int> sortArray(vector<int> &nums)
{
int length = nums.size();
if (length == 1)
return nums;
int inc = length;
while (true)
{
inc /= 2;
for (int k = 0; k < inc; ++k)
for (int i = k + inc; i < length; i += inc)
{
int preIdx = i - inc;
int curVal = nums[i];
while (preIdx >= 0 && curVal < nums[preIdx])
{
nums[preIdx + inc] = nums[preIdx];
preIdx -= inc;
}
nums[preIdx + inc] = curVal;
}
if (inc == 1)
break;
}
return nums;
}
};
```
### E
```cpp
class Solution
{
vector<int> nums;
public:
void merge(int left, int right)
{
if (left >= right)
{
return;
}
int mid = (left + right) / 2;
merge(left, mid);
merge(mid + 1, right);
int i = left, j = mid + 1;
vector<int> tmp;
while (i <= mid && j <= right)
{
if (nums[i] < nums[j])
{
tmp.push_back(nums[i]);
i++;
}
else
{
tmp.push_back(nums[j]);
j++;
}
}
while (i <= mid)
{
tmp.push_back(nums[i]);
i++;
}
while (j <= right)
{
tmp.push_back(nums[j]);
j++;
}
for (i = 0; i < right - left + 1; ++i)
nums[i + left] = tmp[i];
}
vector<int> sortArray(vector<int> &nums)
{
this->nums = nums;
int length = nums.size();
if (length == 1)
return nums;
merge(0, nums.size() - 1);
return this->nums;
}
};
```
### F
```cpp
class Solution
{
public:
int partion(vector<int> &nums, int left, int right)
{
int pivot = nums[right];
int i = left, j;
for (j = left; j < right; ++j)
{
if (nums[j] <= pivot)
{
swap(nums[i], nums[j]);
i++;
}
}
swap(nums[i], nums[right]);
return i;
}
int random_partion(vector<int> &nums, int left, int right)
{
int randIdx = rand() % (right - left + 1) + left;
swap(nums[randIdx], nums[right]);
return partion(nums, left, right);
}
void random_quick_sort(vector<int> &nums, int left, int right)
{
if (left < right)
{
int pivot = random_partion(nums, left, right);
random_quick_sort(nums, left, pivot - 1);
random_quick_sort(nums, pivot + 1, right);
}
}
vector<int> sortArray(vector<int> &nums)
{
int length = nums.size();
if (length == 1)
return nums;
srand(time(NULL));
random_quick_sort(nums, 0, length - 1);
return nums;
}
};
```
{
"node_id": "algorithm-b36465af5596480baf353689bbb76872",
"keywords": [
"leetcode",
"环形链表"
],
"children": [],
"export": [
"solution.json"
],
"title": "环形链表"
}
\ No newline at end of file
<p>给定一个链表,判断链表中是否有环。</p>
<p>如果链表中有某个节点,可以通过连续跟踪 <code>next</code> 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 <code>pos</code> 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 <code>pos</code><code>-1</code>,则在该链表中没有环。<strong>注意:<code>pos</code> 不作为参数进行传递</strong>,仅仅是为了标识链表的实际情况。</p>
<p>如果链表中存在环,则返回 <code>true</code> 。 否则,返回 <code>false</code></p>
<p>&nbsp;</p>
<p><strong>进阶:</strong></p>
<p>你能用 <em>O(1)</em>(即,常量)内存解决此问题吗?</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist.png" style="height: 97px; width: 300px;"></p>
<pre><strong>输入:</strong>head = [3,2,0,-4], pos = 1
<strong>输出:</strong>true
<strong>解释:</strong>链表中有一个环,其尾部连接到第二个节点。
</pre>
<p><strong>示例&nbsp;2:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test2.png" style="height: 74px; width: 141px;"></p>
<pre><strong>输入:</strong>head = [1,2], pos = 0
<strong>输出:</strong>true
<strong>解释:</strong>链表中有一个环,其尾部连接到第一个节点。
</pre>
<p><strong>示例 3:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test3.png" style="height: 45px; width: 45px;"></p>
<pre><strong>输入:</strong>head = [1], pos = -1
<strong>输出:</strong>false
<strong>解释:</strong>链表中没有环。
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li>链表中节点的数目范围是 <code>[0, 10<sup>4</sup>]</code></li>
<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
<li><code>pos</code><code>-1</code> 或者链表中的一个 <strong>有效索引</strong></li>
</ul>
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
bool hasCycle(ListNode *head)
{
ListNode *low = head; //慢指针
ListNode *quick = head; //快指针
while (low && quick && quick->next)
{
low = low->next;
quick = quick->next->next;
if (low == quick)
{
return true;
}
}
return false;
}
};
\ No newline at end of file
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "a737e6c0d8fe404096d77d4f2018e2b0"
}
\ No newline at end of file
# 环形链表
<p>给定一个链表,判断链表中是否有环。</p>
<p>如果链表中有某个节点,可以通过连续跟踪 <code>next</code> 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 <code>pos</code> 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 <code>pos</code><code>-1</code>,则在该链表中没有环。<strong>注意:<code>pos</code> 不作为参数进行传递</strong>,仅仅是为了标识链表的实际情况。</p>
<p>如果链表中存在环,则返回 <code>true</code> 。 否则,返回 <code>false</code></p>
<p>&nbsp;</p>
<p><strong>进阶:</strong></p>
<p>你能用 <em>O(1)</em>(即,常量)内存解决此问题吗?</p>
<p>&nbsp;</p>
<p><strong>示例 1:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist.png" style="height: 97px; width: 300px;"></p>
<pre><strong>输入:</strong>head = [3,2,0,-4], pos = 1
<strong>输出:</strong>true
<strong>解释:</strong>链表中有一个环,其尾部连接到第二个节点。
</pre>
<p><strong>示例&nbsp;2:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test2.png" style="height: 74px; width: 141px;"></p>
<pre><strong>输入:</strong>head = [1,2], pos = 0
<strong>输出:</strong>true
<strong>解释:</strong>链表中有一个环,其尾部连接到第一个节点。
</pre>
<p><strong>示例 3:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test3.png" style="height: 45px; width: 45px;"></p>
<pre><strong>输入:</strong>head = [1], pos = -1
<strong>输出:</strong>false
<strong>解释:</strong>链表中没有环。
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li>链表中节点的数目范围是 <code>[0, 10<sup>4</sup>]</code></li>
<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
<li><code>pos</code><code>-1</code> 或者链表中的一个 <strong>有效索引</strong></li>
</ul>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
```
### after
```cpp
```
## 答案
```cpp
class Solution
{
public:
bool hasCycle(ListNode *head)
{
ListNode *low = head;
ListNode *quick = head;
while (low && quick && quick->next)
{
low = low->next;
quick = quick->next;
if (low == quick)
{
return true;
}
}
return false;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
bool hasCycle(ListNode *head)
{
ListNode *q = head;
while (q)
{
if (q->visit == true)
return true;
else
q->visit = true;
}
return false;
}
};
```
### B
```cpp
class Solution
{
public:
bool hasCycle(ListNode *head)
{
if (head == NULL || head->next == NULL)
return false;
ListNode *k = head;
ListNode *q = head->next;
int count = 0;
while (q)
{
for (int i = count; i > 0; i--)
{
k = k->next;
if (k == q)
return true;
}
k = head;
q = q->next;
count++;
}
return false;
}
};
```
### C
```cpp
class Solution
{
public:
bool hasCycle(ListNode *head)
{
if (head == NULL || head->next == NULL)
return false;
ListNode *Snode = head;
ListNode *Fnode = head->next;
while (Snode != Fnode)
{
if (Fnode == NULL || Fnode->next == NULL)
{
return false;
}
Snode = Snode->next;
Fnode = Fnode->next->next;
}
return true;
}
};
```
{
"node_id": "algorithm-dc2fe764852f445ea4f7393548a21e83",
"keywords": [
"leetcode",
"环形链表 II"
],
"children": [],
"export": [
"solution.json"
],
"title": "环形链表 II"
}
\ No newline at end of file
<p>给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 <code>null</code></p>
<p>为了表示给定链表中的环,我们使用整数 <code>pos</code> 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 <code>pos</code><code>-1</code>,则在该链表中没有环。<strong>注意,<code>pos</code> 仅仅是用于标识环的情况,并不会作为参数传递到函数中。</strong></p>
<p><strong>说明:</strong>不允许修改给定的链表。</p>
<p><strong>进阶:</strong></p>
<ul>
<li>你是否可以使用 <code>O(1)</code> 空间解决此题?</li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist.png" style="height: 97px; width: 300px;" /></p>
<pre>
<strong>输入:</strong>head = [3,2,0,-4], pos = 1
<strong>输出:</strong>返回索引为 1 的链表节点
<strong>解释:</strong>链表中有一个环,其尾部连接到第二个节点。
</pre>
<p><strong>示例 2:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test2.png" style="height: 74px; width: 141px;" /></p>
<pre>
<strong>输入:</strong>head = [1,2], pos = 0
<strong>输出:</strong>返回索引为 0 的链表节点
<strong>解释:</strong>链表中有一个环,其尾部连接到第一个节点。
</pre>
<p><strong>示例 3:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test3.png" style="height: 45px; width: 45px;" /></p>
<pre>
<strong>输入:</strong>head = [1], pos = -1
<strong>输出:</strong>返回 null
<strong>解释:</strong>链表中没有环。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>链表中节点的数目范围在范围 <code>[0, 10<sup>4</sup>]</code></li>
<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
<li><code>pos</code> 的值为 <code>-1</code> 或者链表中的一个有效索引</li>
</ul>
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
ListNode *slow = head; //记录慢指针
ListNode *fast = head; //记录快指针
ListNode *meet = NULL; //记录相遇点
while (slow && fast && fast->next)
{ //找出相遇点
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
meet = slow;
break;
}
}
while (head && meet)
{ //根据相遇的的位置找出环的入口点
if (meet == head)
{
break;
}
head = head->next;
meet = meet->next;
}
return meet;
}
};
\ No newline at end of file
{
"type": "code_options",
"author": "CSDN.net",
"source": "solution.md",
"exercise_id": "205ab2303cd64cc4bd18e156ab4af1ff"
}
\ No newline at end of file
# 环形链表 II
<p>给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 <code>null</code></p>
<p>为了表示给定链表中的环,我们使用整数 <code>pos</code> 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 <code>pos</code><code>-1</code>,则在该链表中没有环。<strong>注意,<code>pos</code> 仅仅是用于标识环的情况,并不会作为参数传递到函数中。</strong></p>
<p><strong>说明:</strong>不允许修改给定的链表。</p>
<p><strong>进阶:</strong></p>
<ul>
<li>你是否可以使用 <code>O(1)</code> 空间解决此题?</li>
</ul>
<p> </p>
<p><strong>示例 1:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist.png" style="height: 97px; width: 300px;" /></p>
<pre>
<strong>输入:</strong>head = [3,2,0,-4], pos = 1
<strong>输出:</strong>返回索引为 1 的链表节点
<strong>解释:</strong>链表中有一个环,其尾部连接到第二个节点。
</pre>
<p><strong>示例 2:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test2.png" style="height: 74px; width: 141px;" /></p>
<pre>
<strong>输入:</strong>head = [1,2], pos = 0
<strong>输出:</strong>返回索引为 0 的链表节点
<strong>解释:</strong>链表中有一个环,其尾部连接到第一个节点。
</pre>
<p><strong>示例 3:</strong></p>
<p><img alt="" src="https://assets.leetcode-cn.com/aliyun-lc-upload/uploads/2018/12/07/circularlinkedlist_test3.png" style="height: 45px; width: 45px;" /></p>
<pre>
<strong>输入:</strong>head = [1], pos = -1
<strong>输出:</strong>返回 null
<strong>解释:</strong>链表中没有环。
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li>链表中节点的数目范围在范围 <code>[0, 10<sup>4</sup>]</code></li>
<li><code>-10<sup>5</sup> <= Node.val <= 10<sup>5</sup></code></li>
<li><code>pos</code> 的值为 <code>-1</code> 或者链表中的一个有效索引</li>
</ul>
<p>以下错误的选项是?</p>
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
```
### after
```cpp
```
## 答案
```cpp
class Solution
{
public:
vector<int> searchRange(vector<int> &nums, int target)
{
int left = 0;
int right = nums.size() - 1;
vector<int> res = {-1, -1};
bool find = false;
while (right >= left && find == false && nums[left] <= target)
{
int mid = (left + right) / 2;
if (nums[mid] > target)
right = mid - 1;
else if (nums[mid] < target)
left = mid + 1;
else
{
find = true;
while (mid > 0 && nums[mid - 1] == target)
mid++;
res[0] = mid;
while (mid < nums.size() - 1 && nums[mid + 1] == target)
mid--;
res[1] = mid;
}
}
return res;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
set<ListNode *> node_set;
while (head)
{
if (node_set.find(head) != node_set.end())
{
return head;
}
node_set.insert(head);
head = head->next;
}
return NULL;
}
};
```
### B
```cpp
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
ListNode *slow = head;
ListNode *fast = head;
ListNode *meet = NULL;
while (slow && fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
meet = slow;
break;
}
}
while (head && meet)
{
if (meet == head)
{
break;
}
head = head->next;
meet = meet->next;
}
return meet;
}
};
```
### C
```cpp
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
if (!head || !head->next)
return NULL;
ListNode *slow = head, *fast = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
break;
}
if (slow != fast)
return NULL;
slow = head;
while (slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
```
......@@ -54,7 +54,15 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
```
### after
```cpp
......@@ -63,21 +71,98 @@
## 答案
```cpp
class Solution
{
public:
bool hasCycle(ListNode *head)
{
ListNode *low = head;
ListNode *quick = head;
while (low && quick && quick->next)
{
low = low->next;
quick = quick->next;
if (low == quick)
{
return true;
}
}
return false;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
bool hasCycle(ListNode *head)
{
ListNode *q = head;
while (q)
{
if (q->visit == true)
return true;
else
q->visit = true;
}
return false;
}
};
```
### B
```cpp
class Solution
{
public:
bool hasCycle(ListNode *head)
{
if (head == NULL || head->next == NULL)
return false;
ListNode *k = head;
ListNode *q = head->next;
int count = 0;
while (q)
{
for (int i = count; i > 0; i--)
{
k = k->next;
if (k == q)
return true;
}
k = head;
q = q->next;
count++;
}
return false;
}
};
```
### C
```cpp
class Solution
{
public:
bool hasCycle(ListNode *head)
{
if (head == NULL || head->next == NULL)
return false;
ListNode *Snode = head;
ListNode *Fnode = head->next;
while (Snode != Fnode)
{
if (Fnode == NULL || Fnode->next == NULL)
{
return false;
}
Snode = Snode->next;
Fnode = Fnode->next->next;
}
return true;
}
};
```
......@@ -57,7 +57,15 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
```
### after
```cpp
......@@ -66,21 +74,121 @@
## 答案
```cpp
class Solution
{
public:
vector<int> searchRange(vector<int> &nums, int target)
{
int left = 0;
int right = nums.size() - 1;
vector<int> res = {-1, -1};
bool find = false;
while (right >= left && find == false && nums[left] <= target)
{
int mid = (left + right) / 2;
if (nums[mid] > target)
right = mid - 1;
else if (nums[mid] < target)
left = mid + 1;
else
{
find = true;
while (mid > 0 && nums[mid - 1] == target)
mid++;
res[0] = mid;
while (mid < nums.size() - 1 && nums[mid + 1] == target)
mid--;
res[1] = mid;
}
}
return res;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
set<ListNode *> node_set;
while (head)
{
if (node_set.find(head) != node_set.end())
{
return head;
}
node_set.insert(head);
head = head->next;
}
return NULL;
}
};
```
### B
```cpp
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
ListNode *slow = head;
ListNode *fast = head;
ListNode *meet = NULL;
while (slow && fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
meet = slow;
break;
}
}
while (head && meet)
{
if (meet == head)
{
break;
}
head = head->next;
meet = meet->next;
}
return meet;
}
};
```
### C
```cpp
class Solution
{
public:
ListNode *detectCycle(ListNode *head)
{
if (!head || !head->next)
return NULL;
ListNode *slow = head, *fast = head;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
break;
}
if (slow != fast)
return NULL;
slow = head;
while (slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
```
......@@ -42,30 +42,177 @@ minStack.getMin(); --&gt; 返回 -2.
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(x);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
```
## 答案
```cpp
其他三个都是错的
```
## 选项
### A
```cpp
class MinStack
{
public:
/** initialize your data structure here. */
private:
stack<long int> s;
stack<long int> mins;
public:
MinStack()
{
while (!s.empty())
{
s.pop();
}
while (!mins.empty())
{
mins.pop();
}
}
void push(int x)
{
if (s.empty())
{
s.push(x);
mins.push(x);
}
else
{
if (mins.top() >= x)
{
s.push(x);
mins.push(x);
}
else
{
mins.push(mins.top());
s.push(x);
}
}
}
void pop()
{
s.pop();
mins.pop();
}
int top()
{
return s.top();
}
int getMin()
{
return mins.top();
}
};
```
### B
```cpp
class MinStack
{
public:
/** initialize your data structure here. */
stack<int> s;
MinStack()
{
}
void push(int x)
{
if (s.empty())
{
s.push(x);
s.push(x);
}
else
{
int temp = s.top();
s.push(x);
if (x < temp)
{
s.push(x);
}
else
{
s.push(temp);
}
}
}
void pop()
{
s.pop();
s.pop();
}
int top()
{
int temp = s.top();
s.pop();
int top = s.top();
s.push(temp);
return top;
}
int getMin()
{
return s.top();
}
};
```
### C
```cpp
class MinStack
{
public:
stack<int> s;
stack<int> min;
/** initialize your data structure here. */
MinStack()
{
}
void push(int x)
{
s.push(x);
if (min.empty() || x <= min.top())
{
min.push(x);
}
}
void pop()
{
if (s.top() == min.top())
min.pop();
s.pop();
}
int top()
{
return s.top();
}
int getMin()
{
return min.top();
}
};
```
......@@ -26,30 +26,161 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
int res;
vector<int> nums = {3, 6, 9, 1};
res = sol.maximumGap(nums);
cout << res;
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int maximumGap(vector<int> &nums)
{
int l = 0, r = nums.size() - 1;
while (l < r)
{
int mid = (l + r) / 2;
if (nums[mid] < nums[mid + 1])
l = mid + 1;
else
r = mid;
}
return r;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int maximumGap(vector<int> &nums)
{
if (nums.size() < 2)
return 0;
if (nums.size() == 2)
return abs(nums[1] - nums[0]);
int maxn = 0;
int minn = INT_MAX;
for (int i = 0; i < nums.size(); i++)
maxn = max(maxn, nums[i]);
for (int i = 0; i < nums.size(); i++)
minn = min(minn, nums[i]);
if (maxn == minn)
return 0;
int size = (maxn - minn) / nums.size();
if (size < 1)
size = 1;
int num = (maxn - minn) / size + 1;
vector<int> nummax(num, 0);
vector<int> nummin(num, maxn);
nummin[0] = minn;
nummax[0] = minn;
nummax[num - 1] = maxn;
nummin[num - 1] = maxn;
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == maxn || nums[i] == minn)
continue;
int qnum = (nums[i] - minn) / size;
nummax[qnum] = max(nummax[qnum], nums[i]);
nummin[qnum] = min(nummin[qnum], nums[i]);
}
for (int i = 0; i < nummin.size(); i++)
{
if (nummax[i] == 0 && nummin[i] == maxn)
{
nummax.erase(nummax.begin() + i);
nummin.erase(nummin.begin() + i);
i--;
}
}
int res = 0;
for (int i = 1; i < nummax.size(); i++)
{
res = max(res, nummin[i] - nummax[i - 1]);
}
return res;
}
};
```
### B
```cpp
class Solution
{
public:
int maximumGap(vector<int> &nums)
{
if (nums.empty())
return 0;
int mx = INT_MIN, mn = INT_MAX, n = nums.size();
for (int a : nums)
{
mx = max(a, mx);
mn = min(a, mn);
}
int size = (mx - mn) / n + 1;
int bucket_nums = (mx - mn) / size + 1;
vector<int> bucket_min(bucket_nums, INT_MAX);
vector<int> bucket_max(bucket_nums, INT_MIN);
set<int> s;
for (int a : nums)
{
int indx = (a - mn) / size;
bucket_max[indx] = max(bucket_max[indx], a);
bucket_min[indx] = min(bucket_min[indx], a);
s.insert(indx);
}
int pre = 0, ans = 0;
for (int i = 1; i < bucket_nums; ++i)
{
if (!s.count(i))
continue;
int t = bucket_min[i] - bucket_max[pre];
ans = max(ans, t);
pre = i;
}
return ans;
}
};
```
### C
```cpp
class Solution
{
public:
static bool cmp(const int &a, const int &b)
{
return a < b;
}
int maximumGap(vector<int> &nums)
{
if (nums.size() <= 1)
return 0;
sort(nums.begin(), nums.end(), cmp);
int maxgap = 0;
for (int i = 1; i < nums.size(); i++)
{
maxgap = max(maxgap, nums[i] - nums[i - 1]);
}
return maxgap;
}
};
```
class Solution
{
public:
int calculate(string s)
{
stack<int> ops;
ops.push(1);
int sign = 1;
int ret = 0;
int n = s.length();
int i = 0;
while (i < n)
{
if (s[i] == ' ')
{
i++;
}
else if (s[i] == '+')
{
sign = ops.top();
i++;
}
else if (s[i] == '-')
{
// 将后面要算的数都取反
sign = -ops.top();
i++;
}
else if (s[i] == '(')
{
// 括号里面的所有数都用这个sign来计算
ops.push(sign);
i++;
}
else if (s[i] == ')')
{
ops.pop();
i++;
}
else
{
long num = 0;
while (i < n && s[i] >= '0' && s[i] <= '9')
{
num = num * 10 + s[i] - '0';
i++;
}
ret += sign * num;
}
}
return ret;
}
};
......@@ -38,30 +38,403 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
int res;
string s1 = "(1+(4+5+2)-3)+(6+8)";
res = sol.calculate(s1);
cout << res;
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int calculate(string s)
{
stack<string> expr, nums, ops;
int cur = 0, len = s.size();
string tmp = "";
while (cur < len)
{
switch (s[cur])
{
case ' ':
break;
case '+':
case '-':
case '(':
if (tmp != "")
{
expr.push(tmp);
tmp = "";
}
expr.push(tmp + s[cur]);
break;
case ')':
{
if (tmp != "")
{
expr.push(tmp);
tmp = "";
}
int caled = calculate(expr);
expr.push(intToStr(caled));
break;
}
default:
tmp += s[cur];
break;
}
++cur;
}
if (tmp != "")
expr.push(tmp);
return calculate(expr);
}
private:
int calculate(stack<string> &s)
{
stack<int> nums;
stack<char> ops;
string top;
while (!s.empty() && (top = s.top()) != "(")
{
if (top == "+" || top == "-")
ops.push(top[0]);
else
nums.push(strToInt(top));
s.pop();
}
if (!s.empty())
s.pop();
int ans = nums.top(), num;
nums.pop();
while (!ops.empty())
{
num = nums.top();
nums.pop();
if (ops.top() == '+')
ans += num;
else
ans -= num;
}
return ans;
}
int strToInt(string s)
{
int ans = 0, len = s.size();
if (len == 0)
return 0;
int symbol = s[0] == '-' ? -1 : 1;
for (int i = s[0] == '+' || s[0] == '-' ? 1 : 0; i < len; ++i)
{
ans *= 10;
ans += s[i] - '0';
}
return ans * symbol;
}
string intToStr(int num)
{
if (num == 0)
return "0";
int symbol = num >= 0 ? 1 : -1;
string s = "";
num *= symbol;
while (num)
{
s = (char)(num % 10 + '0') + s;
num /= 10;
}
if (symbol == -1)
s = "-" + s;
return s;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int calculate(string s)
{
stack<long> conclude;
stack<char> fuhao;
int i = 0, len = s.length();
while (i < len)
{
if (s[i] == ' ')
i++;
else if (s[i] == '(')
{
fuhao.push('(');
i++;
}
else if (s[i] == ')')
{
if (fuhao.top() != '(')
{
long x = conclude.top();
conclude.pop();
long y = conclude.top();
conclude.pop();
if (fuhao.top() == '+')
conclude.push(y + x);
else
conclude.push(y - x);
fuhao.pop();
}
fuhao.pop();
i++;
}
else if (s[i] == '+' || s[i] == '-')
{
if (!fuhao.empty() && fuhao.top() != '(')
{
long x = conclude.top();
conclude.pop();
long y = conclude.top();
conclude.pop();
if (fuhao.top() == '+')
conclude.push(y + x);
else
conclude.push(y - x);
fuhao.pop();
}
fuhao.push(s[i]);
i++;
}
else
{
long x = s[i] - '0';
i++;
while (i < len && s[i] <= '9' && s[i] >= '0')
{
x = x * 10 + (s[i] - '0');
i++;
}
conclude.push(x);
}
}
if (!fuhao.empty())
{
long x = conclude.top();
conclude.pop();
long y = conclude.top();
conclude.pop();
if (fuhao.top() == '+')
conclude.push(y + x);
else
conclude.push(y - x);
fuhao.pop();
}
return conclude.top();
}
};
```
### B
```cpp
class Solution
{
public:
int calculate(string s)
{
static const int STATE_BEGIN = 0;
static const int NUMBER_STATE = 1;
static const int OPERATION_STATE = 2;
long number = 0;
int STATE = STATE_BEGIN;
int computer_flag = 0;
for (int i = 0; i < s.length(); i++)
{
if (s[i] == ' ')
{
continue;
}
switch (STATE)
{
case STATE_BEGIN:
if (s[i] >= '0' && s[i] <= '9')
{
STATE = NUMBER_STATE;
}
else
{
STATE = OPERATION_STATE;
}
i--;
break;
case NUMBER_STATE:
if (s[i] >= '0' && s[i] <= '9')
{
number = number * 10 + s[i] - '0';
}
else
{
number_stack.push(number);
if (computer_flag == 1)
{
computer(number_stack, operation_stack);
}
number = 0;
i--;
STATE = OPERATION_STATE;
}
break;
case OPERATION_STATE:
if (s[i] == '+' || s[i] == '-')
{
operation_stack.push(s[i]);
computer_flag = 1;
}
else if (s[i] == '(')
{
computer_flag = 0;
}
else if (s[i] >= '0' && s[i] <= '9')
{
STATE = NUMBER_STATE;
i--;
}
else if (s[i] == ')')
{
computer(number_stack, operation_stack);
}
break;
}
}
if (number != 0)
{
number_stack.push(number);
computer(number_stack, operation_stack);
}
if (number == 0 && number_stack.empty())
{
return 0;
}
return number_stack.top();
}
void computer(stack<long> &number_stack, stack<char> &operation_stack)
{
if (number_stack.size() < 2)
{
return;
}
int num2 = number_stack.top();
number_stack.pop();
int num1 = number_stack.top();
number_stack.pop();
if (operation_stack.top() == '+')
{
number_stack.push(num1 + num2);
}
else if (operation_stack.top() == '-')
{
number_stack.push(num1 - num2);
}
operation_stack.pop();
}
private:
stack<long> number_stack;
stack<char> operation_stack;
};
```
### C
```cpp
class Solution
{
public:
void sum(vector<string> &stk)
{
vector<string> temp;
while (!stk.empty() && stk.back() != "(")
{
temp.push_back(stk.back());
stk.pop_back();
}
if (!stk.empty() && stk.back() == "(")
stk.pop_back();
if (temp.back() != "-")
temp.emplace_back("+");
reverse(temp.begin(), temp.end());
int ret = 0;
int n = temp.size();
for (int i = 0; i < n - 1; i += 2)
{
int num = stoi(temp[i + 1]);
if (temp[i] == "-")
num *= (-1);
ret += num;
}
stk.push_back(to_string(ret));
}
int calculate(string s)
{
vector<string> stk;
int n = s.size();
int ret = 0;
string temp;
for (int i = 0; i < n; ++i)
{
if (isdigit(s[i]))
{
temp += s[i];
}
else if (s[i] == '+' || s[i] == '-')
{
if (!temp.empty())
{
stk.push_back(temp);
temp.clear();
}
temp += s[i];
stk.push_back(temp);
temp.clear();
}
else if (s[i] == '(')
{
temp += s[i];
stk.push_back(temp);
temp.clear();
}
else if (s[i] == ')')
{
stk.push_back(temp);
temp.clear();
sum(stk);
}
}
if (!temp.empty())
stk.push_back(temp);
sum(stk);
if (stk.size() == 1)
ret = stoi(stk[0]);
return ret;
}
};
```
class Solution
{
public:
int calculate(string s)
{
vector<int> stk;
char preSign = '+';
int num = 0;
int n = s.length();
for (int i = 0; i < n; ++i)
{
if (isdigit(s[i]))
{
num = num * 10 + int(s[i] - '0');
}
if (!isdigit(s[i]) && s[i] != ' ' || i == n - 1)
{
switch (preSign)
{
case '+':
stk.push_back(num);
break;
case '-':
stk.push_back(-num);
break;
case '*':
stk.back() *= num;
break;
default:
stk.back() /= num;
}
preSign = s[i];
num = 0;
}
}
return accumulate(stk.begin(), stk.end(), 0);
}
};
......@@ -46,30 +46,256 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
int res;
string s1 = "3+2*2";
res = sol.calculate(s1);
cout << res;
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int calculate(string s)
{
int res = 0;
stack<int> my_stack{};
vector<char> my_vec{};
for (auto x : s)
{
if (x != ' ')
my_vec.push_back(x);
}
int start = 0;
int end = 0;
int tmp = 0;
while (start != my_vec.size())
{
tmp = 0;
for (int i = start; i < my_vec.size(); i++)
{
if (my_vec[i] >= '0')
{
if (i == 0)
{
tmp = my_vec[i] - '0';
}
else if (my_vec[i - 1] == '+' || my_vec[i - 1] == '*' || my_vec[i - 1] == '/')
tmp = my_vec[i] - '0';
else if (my_vec[i - 1] == '-')
tmp = -1 * (my_vec[i] - '0');
else if (my_vec[i - 1] >= '0')
{
if (tmp >= 0)
tmp = tmp * 10 + (my_vec[i] - '0');
else
tmp = tmp * 10 - (my_vec[i] - '0');
}
if (i == my_vec.size() - 1)
end = i;
}
else
{
end = i;
break;
}
}
if (start == 0)
my_stack.push(tmp);
else
{
if (my_vec[start - 1] == '+' || my_vec[start - 1] == '-')
my_stack.push(tmp);
else if (my_vec[start - 1] == '*')
my_stack.top() = my_stack.top() * tmp;
else if (my_vec[start - 1] == '/')
my_stack.top() = my_stack.top() / tmp;
}
start = end + 1;
}
while (!my_stack.empty())
{
res = my_stack.top();
my_stack.pop();
}
return res;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int calculate(string s)
{
int ans = 0;
int n = s.size();
char ope = '+';
stack<int> temp;
int d = 0;
int A;
for (int i = 0; i < n; i++)
{
if (s[i] - '0' >= 0 && s[i] - '0' <= 9)
{
d = d * 10 + (s[i] - '0');
}
if ((s[i] < '0' && s[i] != ' ') || i == n - 1)
{
if (ope == '+')
{
temp.push(d);
}
if (ope == '-')
{
temp.push(-d);
}
if (ope == '*')
{
A = temp.top() * d;
temp.pop();
temp.push(A);
}
if (ope == '/')
{
A = temp.top() / d;
temp.pop();
temp.push(A);
}
ope = s[i];
d = 0;
}
}
while (!temp.empty())
{
ans += temp.top();
temp.pop();
}
return ans;
}
};
```
### B
```cpp
class Solution
{
public:
int calculate(string s)
{
stack<char> fuhao;
stack<long> conclude;
int i = 0, len = s.length();
while (i < len)
{
if (s[i] == ' ')
i++;
else if (s[i] >= '0' && s[i] <= '9')
{
long x = s[i] - '0';
i++;
while (i < len && s[i] >= '0' && s[i] <= '9')
{
x = x * 10 + s[i] - '0';
i++;
}
conclude.push(x);
}
else
{
while (!fuhao.empty() && (fuhao.top() == '*' || fuhao.top() == '/' || s[i] == '+' || s[i] == '-'))
{
long x = conclude.top();
conclude.pop();
long y = conclude.top();
conclude.pop();
if (fuhao.top() == '+')
conclude.push(y + x);
else if (fuhao.top() == '-')
conclude.push(y - x);
else if (fuhao.top() == '*')
conclude.push(y * x);
else
conclude.push(y / x);
fuhao.pop();
}
fuhao.push(s[i]);
i++;
}
}
while (!fuhao.empty())
{
long x = conclude.top();
conclude.pop();
long y = conclude.top();
conclude.pop();
if (fuhao.top() == '+')
conclude.push(y + x);
else if (fuhao.top() == '-')
conclude.push(y - x);
else if (fuhao.top() == '*')
conclude.push(y * x);
else
conclude.push(y / x);
fuhao.pop();
}
return conclude.top();
}
};
```
### C
```cpp
class Solution
{
public:
int calculate(string s)
{
vector<int> stk;
char preSign = '+';
int num = 0;
int n = s.length();
for (int i = 0; i < n; ++i)
{
if (isdigit(s[i]))
{
num = num * 10 + int(s[i] - '0');
}
if (!isdigit(s[i]) && s[i] != ' ' || i == n - 1)
{
switch (preSign)
{
case '+':
stk.push_back(num);
break;
case '-':
stk.push_back(-num);
break;
case '*':
stk.back() *= num;
break;
default:
stk.back() /= num;
}
preSign = s[i];
num = 0;
}
}
return accumulate(stk.begin(), stk.end(), 0);
}
};
```
......@@ -42,30 +42,222 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
vector<int> res;
vector<int> nums = {5, 2, 6, 1};
res = sol.countSmaller(nums);
for (auto i : res)
cout << i << " ";
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int lowbit(int x)
{
return (int)x & (-1 * x);
}
int getSum(int x, vector<int> &c)
{
int sum = 0;
for (int i = x; i > 0; i -= lowbit(i))
{
sum += c[i];
}
return sum;
}
void update(vector<int> &c, int x, int v)
{
for (int i = x; i < c.size(); i += lowbit(i))
{
c[i] += v;
}
}
vector<int> countSmaller(vector<int> &nums)
{
vector<int> count;
set<int> ss;
for (auto t : nums)
{
ss.insert(t);
}
unordered_map<int, int> m;
int n = ss.size();
auto it = ss.begin();
for (int i = 1; i <= n; i++)
{
it++;
m[*it] = i;
}
vector<int> sum(n + 1, 0);
for (auto it = nums.rbegin(); it != nums.rend(); it++)
{
int res = 0;
int idx = m[*it];
if (idx > 1)
{
res = getSum(idx - 1, sum);
}
update(sum, m[*it], 1);
count.push_back(res);
}
reverse(count.begin(), count.end());
return count;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
vector<int> countSmaller(vector<int> &nums)
{
vector<int> res(nums.size(), 0);
vector<int> indexs(nums.size(), 0);
for (int i = 0; i < indexs.size(); i++)
{
indexs[i] = i;
}
vector<int> tempindexs(indexs.size(), 0);
mergeSort(nums, indexs, tempindexs, res, 0, nums.size() - 1);
return res;
}
void mergeSort(vector<int> &nums, vector<int> &indexs, vector<int> &tempindexs, vector<int> &res, int left, int right)
{
if (left >= right)
return;
int mid = left + (right - left) / 2;
mergeSort(nums, indexs, tempindexs, res, left, mid);
mergeSort(nums, indexs, tempindexs, res, mid + 1, right);
int i = left;
int j = mid + 1;
int t = 0;
while (i <= mid && j <= right)
{
if (nums[indexs[i]] > nums[indexs[j]])
{
for (int k = i; k <= mid; k++)
{
res[indexs[k]]++;
}
tempindexs[t++] = indexs[j++];
}
else
{
tempindexs[t++] = indexs[i++];
}
}
while (i <= mid)
{
tempindexs[t++] = indexs[i++];
}
while (j <= right)
{
tempindexs[t++] = indexs[j++];
}
t = 0;
while (left <= right)
{
indexs[left++] = tempindexs[t++];
}
}
};
```
### B
```cpp
struct BSTNode
{
int val;
int count;
BSTNode *left;
BSTNode *right;
BSTNode(int x) : val(x), left(NULL), right(NULL), count(0) {}
};
void BST_insert(BSTNode *node, BSTNode *insert_node, int &count_small)
{
if (node->val >= insert_node->val)
{
node->count++;
if (node->left)
BST_insert(node->left, insert_node, count_small);
else
node->left = insert_node;
}
else
{
count_small += node->count + 1;
if (node->right)
BST_insert(node->right, insert_node, count_small);
else
node->right = insert_node;
}
}
class Solution
{
public:
vector<int> countSmaller(vector<int> &nums)
{
int n = nums.size();
if (!n)
return {};
vector<int> count;
count.push_back(0);
BSTNode *node = new BSTNode(nums[n - 1]);
int count_small;
for (int i = 1; i < n; ++i)
{
count_small = 0;
BST_insert(node, new BSTNode(nums[n - i - 1]), count_small);
count.push_back(count_small);
}
delete node;
reverse(count.begin(), count.end());
return count;
}
};
```
### C
```cpp
class Solution
{
public:
vector<int> help;
vector<int> countSmaller(vector<int> &nums)
{
int n = nums.size();
if (n == 0)
return vector<int>();
vector<int> res(n, 0);
for (int i = n - 1; i >= 0; --i)
{
auto it = lower_bound(help.begin(), help.end(), nums[i]);
res[i] = it - help.begin();
help.insert(it, nums[i]);
}
return res;
}
};
```
......@@ -34,30 +34,156 @@
## aop
### before
```cpp
#include <bits/stdc++.h>
using namespace std;
```
### after
```cpp
int main()
{
Solution sol;
int res;
vector<int> nums = {-2, 5, -1};
int lower = -2;
int upper = 2;
res = sol.countRangeSum(nums, lower, upper);
cout << res;
return 0;
}
```
## 答案
```cpp
class Solution
{
public:
int lower, upper, res;
long tmp[10000];
void merge(vector<long> &a, int l, int mid, int r)
{
int i = l, j = mid + 1, k = 0;
while (i <= mid && j <= r)
{
if (a[i] <= a[j])
tmp[k++] = a[i++];
else
tmp[k++] = a[j++];
}
while (i <= mid)
tmp[k++] = a[i++];
while (j <= r)
tmp[k++] = a[j++];
copy(tmp, tmp + k, a.begin() + l);
}
void merge_sort(vector<long> &a, int l, int r)
{
if (l >= r)
return;
int mid = l + r - l / 2;
merge_sort(a, l, mid);
merge_sort(a, mid + 1, r);
int k = mid + 1, j = k;
for (int i = l; i <= mid; ++i)
{
while (k <= r && a[k] - a[i] < lower)
++k;
while (j <= r && a[j] - a[i] <= upper)
++j;
res += j - k;
}
if (a[mid] <= a[mid + 1])
return;
merge(a, l, mid, r);
}
int countRangeSum(vector<int> &nums, int lower, int upper)
{
this->lower = lower;
this->upper = upper;
int n = nums.size();
vector<long> presum(n + 1, 0);
for (int i = 0; i < n; ++i)
presum[i] = presum[i] + nums[i];
merge_sort(presum, 0, n);
return res;
}
};
```
## 选项
### A
```cpp
class Solution
{
public:
int countRangeSum(vector<int> &nums, int lower, int upper)
{
int n = nums.size();
long presum = 0;
multiset<long> S;
S.insert(0);
int ret = 0;
for (int i = 0; i < n; i++)
{
presum += nums[i];
ret += distance(S.lower_bound(presum - upper), S.upper_bound(presum - lower));
S.insert(presum);
}
return ret;
}
};
```
### B
```cpp
class Solution
{
public:
int countRangeSum(vector<int> &nums, int lower, int upper)
{
int n = nums.size();
long presum = 0;
vector<long> S(n + 1, 0);
int ret = 0;
for (int i = 1; i <= n; i++)
{
presum += nums[i - 1];
for (int j = 1; j <= i; j++)
{
if (lower <= presum - S[j - 1] && presum - S[j - 1] <= upper)
ret++;
}
S[i] = presum;
}
return ret;
}
};
```
### C
```cpp
class Solution
{
public:
int countRangeSum(vector<int> &nums, int lower, int upper)
{
int count = 0;
for (int i = 0; i < nums.size(); ++i)
{
if (nums[i] <= upper && nums[i] >= lower)
++count;
long sum = nums[i];
for (int j = i + 1; j < nums.size(); ++j)
{
sum += nums[j];
if (sum <= upper && sum >= lower)
++count;
}
}
return count;
}
};
```
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册