LeetCode Weekly Contest 281
阿新 • • 發佈:2022-03-04
class Solution { public: int countEven(int num) { int ans = 0; for(int i=1;i<=num;i++) { int res = 0; int x = i; while(x) { res+= (x%10); x/=10; } if((res&1)==0) { ans++; } } return ans; } };
/** * 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* mergeNodes(ListNode* head) { ListNode* node = head->next; ListNode* pre = head; ListNode* res = head; int ans=0; while(node!=NULL) { if(node->val == 0) { pre->next = new ListNode(ans); pre->next->next = node; pre = node; ans=0; } else { ans+=node->val; } node = node->next; } ListNode* node2 = res->next; while(node2!=NULL&&node2->next!=NULL) { if(node2->next->val == 0) { node2->next = node2->next->next; } node2 = node2->next; } return res->next; } };
貪心
class Solution { public: int a[30]; string repeatLimitedString(string s, int repeatLimit) { memset(a,0,sizeof(a)); for(int i=0;i<s.length();i++) { a[s[i]-'a']++; } int pos=25; string res=""; while(pos>=0) { int i=0; while(a[pos]>0 && i< repeatLimit) { res+='a'+pos; a[pos]--; i++; if(i==repeatLimit && a[pos]>0) { int j = pos-1; while(j>=0 && a[j]<=0) { j--; } if(j!=-1) { a[j]--; res+='a'+j; i=0; } } } pos--; } return res; } };
讓你算出一個數組有多少對數字的乘積能被K整除。我們可以對陣列中的每個數a[i], 來算a[i+1] - a[n]中有多少個數字和它的乘積是能被k整除的。
如果我們可以知道 最小的x,是的 x*a[i]能被k整除,那麼a[i+1]-a[n]中的每個能整除x的數都是我們要找的數。
那麼這個最小的x怎麼算呢,其實是k/gcd(k, a[i]),
所以我們事先要對k分解因數,然後把陣列中能整除這些因數的元素的個數事先存好。
然後針對每個元素a[i],計算x,再計算a[i+1]-a[n]中能整除x的元素個數
class Solution {
public:
int a[405];
map<int,int> m;
int pos;
long long countPairs(vector<int>& nums, int k) {
pos=0;
for(int i=1;i*i<=k;i++)
{
if(k%i==0)
{
a[pos++] = i;
m[i] = pos-1;
a[pos++] = k/i;
m[k/i] = pos-1;
}
}
int sum[pos][100005];
for(int i=0;i<pos;i++)
{
if(nums[0] % a[i] == 0)
{
sum[i][0] =1;
}
else
{
sum[i][0] = 0;
}
for(int j=1;j<nums.size();j++)
{
if(nums[j] % a[i] == 0)
{
sum[i][j] = sum[i][j-1]+1;
}
else
{
sum[i][j] = sum[i][j-1];
}
}
}
long long int ans=0;
for(int i=0;i<nums.size();i++)
{
int x = k / gcd(nums[i], k);
int j = m[x];
ans+= sum[j][nums.size()-1] - sum[j][i];
}
return ans;
}
int gcd(int x, int y)
{
if(x % y == 0)
return y;
else
return gcd(y, x%y);
}
};