推荐社区:万人千题
今日题解
找出数组的最大公约数
思路:先排序,让用 nums.front() 和 nums.back()取出nums数组中最小的和最大的值
使用while循环,当 max % min 不为零的时候,不断的继续让max对min取余,
结束循环后的min就是最大公约数
class Solution {
public:
int findGCD(vector<int>& nums) {
sort(nums.begin(), nums.end());
int min = nums.front();
int max = nums.back();
int temp = 0;
while(max % min){
temp = min;
min = max%min;
max = temp;
}
return min;
}
};
有效三角形的个数
思路:排序+双指针
class Solution {
public:
int triangleNumber(vector<int>& nums) {
int n = nums.size();
sort(nums.begin(), nums.end());
int ret = 0;
// [left, right] 为第三条边的合法位置
int left, right;
for (int i = 0; i < n; ++i) {
right = i + 2;
for (int j = i + 1; j < n; ++j) {
left = j + 1;
while(right < n && nums[right] < nums[i] + nums[j]) right++;
ret += max(right - left, 0);
}
}
return ret;
}
};
重构字符串
思路:隐约感觉好像做过,但上面显示没提交过(摸棱两可是真的烦人)
推一个好评比较多的题解吧,没办法,确实不会
他的思路和代码:
1、用map统计频率字符频率
2、转为vector(即数组)按频率从大到小排序
3、按奇数位顺序插入,插满之后按偶数位顺序插入
class Solution {
private:
bool static cmp (const pair<int, int>& a, const pair<int, int>& b) {
return a.second > b.second; // 按照频率从大到小排序
}
public:
string reorganizeString(string S) {
unordered_map<char, int> umap;
int maxFreq = 0;
for (char s : S) {
umap[s]++;
maxFreq = max(umap[s], maxFreq);
}
if (2 * maxFreq - 1 > S.size()) return "";
vector<pair<int, int>> vec(umap.begin(), umap.end());
sort(vec.begin(), vec.end(), cmp); // 给频率排个序
string result(S);
int index = 0;// 先按奇数位散开
for (int i = 0; i < vec.size(); i++) {
while (vec[i].second--) {
result[index] = vec[i].first;
index += 2;
if (index >= S.size()) index = 1; // 奇数位插满了插偶数位
}
}
return result;
}
};
最多能完成排序的块
思路:当遍历到第 i 个位置时,如果可以切分为块,那前 i 个位置的最大值一定等于 i 。
否则,一定有比 i 小的数划分到后面的块,那块排序后,一定不满足升序。
class Solution {
public:
int maxChunksToSorted(vector<int>& arr) {
int m = 0, res = 0;
for(int i=0; i<arr.size(); ++i) {
m = max(m, arr[i]);//统计前i个位置的最大元素
if(m == i) ++res;
}
return res;
}
};
删除链表中的节点
思路:都在代码注释里
class Solution {
public:
void deleteNode(ListNode* node) {
//只给出要被删除的节点
node->val = node->next->val;//先把当前节点的值变成下一节点的值
node->next = node->next->next;//把下一节点的位置让给下下节点
}
};
删除链表中的倒数第N个节点
思路:使用快慢指针和哑节点(防止头节点被删掉而引发报错)
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* dummy = new ListNode(0, head);
ListNode* first = head;
ListNode* second = dummy;
for (int i = 0; i < n; ++i) {
first = first->next;//先走
}
while (first) {
first = first->next;
second = second->next;
}
second->next = second->next->next;
ListNode* res = dummy->next;
delete dummy;
return res;
}
};
今天很抱歉哈,大家请原谅我,最近的题目难度都上来了,
我需要再沉淀一下,才能把以前不会的题目做出来。
今天英雄哥给的题目只有四道题,我自己还加了两道吧(flag不能倒)
大家加油