[研究生冲刺][算法实习生]LeetCode刷题日记(Day3)
1560. 圆形赛道上经过次数最多的扇区(第203场周赛issue 1)
思路:
主要是分情况讨论,具体代码有点乱,后面将会改进。
算法的复杂度:
算法的时间复杂度为O(n)。算法的空间复杂度为O(n)。
代码:
class Solution {
public:
vector<int> mostVisited(int n, vector<int>& rounds) {
vector<int> res;
int begin = 0, end = 0;
if(rounds.back() == rounds[0])
{
res.push_back(rounds[0]);
}
else if(rounds.back() > rounds[0])
{
begin = rounds[0];
end = rounds.back();
while(begin <= end)
{
res.push_back(begin);
++begin;
}
}
else
{
begin = rounds.back();
end = rounds[0];
for(int i = 1; i<= begin; ++i)
res.push_back(i);
while(end <= n)
{
res.push_back(end);
++end;
}
}
return res;
}
};
1561. 你可以获得的最大硬币数目(第203场周赛issue 2)
思路:
假设有3n堆硬币,首先让Bob取走最少的n堆,然后你和Alice只要依次从最大堆中进行选择即可,因此只要做一个排序,然后舍弃最少的n堆,再间隔着取硬币即可。
算法的复杂度:
算法的时间复杂度为O(nlogn + n) = O(nlogn)。因为没有产生额外空间,所以算法的空间复杂度为O(1)。
代码:
class Solution {
public:
int maxCoins(vector<int>& piles) {
sort(piles.begin(), piles.end());
int n = piles.size() / 3;
int res = 0;
for(int i = n; i < 3 * n; ++i, ++i)
{
res += piles[i];
}
return res;
}
};