1.找出中枢整数
Solution
class Solution {
public:
int pivotInteger(int n) {
int sum = (1 + n)* n / 2;
int tmp = (int)sqrt(sum);
return tmp * tmp == sum ? tmp : -1;
}
};
2.追加字符以获得子序列
Solution
class Solution {
public:
int appendCharacters(string s, string t) {
int i,j;
for(i = 0, j = 0;i < s.size();i++){
if(s[i] == t[j]){
j++;
}
}
return t.size() - j;
}
};
3.从链表中移除节点
Solution
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNodes(ListNode* head) {
//将链表放入数组
vector<int>a;
for(ListNode *i = head; i != nullptr;i = i->next){
a.push_back(i->val);
}
//判断哪些数可以放入
int n = a.size();
int maxnn = -1;
vector<int>ans;
for(int i = n-1; i >= 0;i--){
if(maxnn <= a[i]) ans.push_back(a[i]);
maxnn = max(maxnn, a[i]);
}
reverse(ans.begin(), ans.end());
//建立链表
ListNode *fake = new ListNode();
ListNode *now = fake;
for (int x : ans) {
ListNode *node = new ListNode(x);
now->next = node;
now = node;
}
ListNode *ret = fake->next;
delete fake;
return ret;
}
};
4.统计中位数为 K 的子数组
Solution
class Solution {
public:
int countSubarrays(vector<int> &nums, int k) {
int pos = find(nums.begin(), nums.end(), k) - nums.begin(), n = nums.size();
unordered_map<int, int> cnt;
cnt[0] = 1; // i=pos 的时候 c 是 0,直接记到 cnt 中,这样下面不是大于就是小于
for (int i = pos + 1, c = 0; i < n; ++i) {
c += nums[i] > k ? 1 : -1;
++cnt[c];
}
int ans = cnt[0] + cnt[1]; // i=pos 的时候 c 是 0,直接加到答案中,这样下面不是大于就是小于
for (int i = pos - 1, c = 0; i >= 0; --i) {
c += nums[i] < k ? 1 : -1;
ans += cnt[c] + cnt[c + 1];
}
return ans;
}
};
标签:周赛,cnt,ListNode,nums,int,Solution,next,321
From: https://www.cnblogs.com/TTS-TTS/p/17031965.html