LeetCode日记2020.2.13
文章目录
排序专题
969 煎饼排序(mid)
class Solution {
public:
vector<int> pancakeSort(vector<int>& A) {
vector<int> res;
for(int i=0;i<A.size()-1;++i)
{
auto End = A.begin();
advance(End, A.size()-i);
auto maxE = max_element(A.begin(), End);
++maxE;
if(maxE!= End)
{
if(maxE!=A.begin())
{
res.push_back(maxE - A.begin());
reverse(A.begin(),maxE);
}
res.push_back(A.size()-i);
reverse(A.begin(), End);
}
}
return res;
}
};
75 颜色分类(mid)
不如就叫插入计数排序。
class Solution {
public:
void sortColors(vector<int>& nums) {
int cnts[2] = {0, 0};
int i=0;
while(i<nums.size())
{
if(nums[i] != 2)
{
if(nums[i] == 0)
{
swap(nums[cnts[0]], nums[i]);
++cnts[0];
if(cnts[1]!=0)
swap(nums[cnts[0] + cnts[1] - 1], nums[i]);
}
else
{
swap(nums[cnts[0] + cnts[1]], nums[i]);
++cnts[1];
}
}
++i;
}
}
};
剑指 面试题45(mid)
自定义排序。
class Solution {
public:
string minNumber(vector<int>& nums) {
vector<string> ss;
for(auto i: nums)
ss.push_back(to_string(i));
sort(ss.begin(), ss.end(), [](const string& s1, const string& s2){
return s1+s2 < s2+s1;
});
string res;
for(const auto& s: ss)
res += s;
return res;
}
};
524 通过删除字母匹配到字典里最长单词(mid)
class Solution {
public:
string findLongestWord(string s, vector<string>& d) {
string res;
for(const auto& c: d)
{
if(match(s, c))
{
if(res.empty())
res = c;
else if(res.size()<c.size())
res = c;
else if(res.size() == c.size() && res > c)
res = c;
else;
}
}
return res;
}
bool match(const string& s, const string& f)
{
size_t beg = 0;
for(const auto& c: f)
{
auto pos = s.find(c, beg);
if(pos == string::npos)
return false;
beg = pos + 1;
}
return true;
}
};
274 H指数(mid)
class Solution {
public:
int hIndex(vector<int>& citations) {
int n = citations.size();
vector<int> ps(n + 1, 0);
for(auto& c: citations)
++ps[min(c, n)];
for(int s = ps[n]; n > s; s += ps[--n]);
return n;
}
};
275 H指数2(mid)
有序二分。
class Solution {
public:
int hIndex(vector<int>& citations) {
int beg = 0, End = citations.size();
int n = End;
while(beg + 1 < End)
{
int mid = (beg + End) / 2;
if(citations[mid] <= n - mid)
beg = mid;
else
End = mid;
}
int h = n - beg;
if(h>0&&citations[beg]<h)
--h;
return h;
}
};
224 基本计算器(hard)
遇(
入栈,遇)
出栈,缓存左侧操作数与运算符,出栈时计算。
class Solution {
public:
int calculate(string s) {
stack<pair<int, char>> st;
st.push(make_pair(0, '+'));
for(int i=0; i<s.size(); ++i)
{
char c = s[i];
if(c == '(')
{
st.push(make_pair(0, '+'));
}
else if(c == ')')
{
int r = st.top().first;
st.pop();
st.top().first = cal(st.top().first, r, st.top().second);
}
else if(c == '+' || c == '-')
{
st.top().second = c;
}
else if(isdigit(c))
{
string dig;
while(isdigit(s[i]) || s[i] == ' ')
{
if(isdigit(s[i]))
dig.append(1, s[i]);
++i;
}
st.top().first = cal(st.top().first, stoi(dig), st.top().second);
--i;
}
else;
}
return st.top().first;
}
int cal(int l, int r, char op)
{
switch(op)
{
case '+':
return l+r;
case '-':
return l-r;
case '*':
return l*r;
case '/':
return l/r;
default:
return l+r;
}
}
};