?
?
?
lc854
偶數之間的奇數個數 = 差值/2 先都變成偶數
把整個范圍包起來,反正偶數不做數
class Solution {
public int countOdds(int low, int high) {
if(low % 2 == 1){
--low;
}
if(high % 2 == 1){
++high;
}
return (high - low) / 2;
}
}
?
lc17.10
摩爾投票
?class Solution {
public:
int majorityElement(vector<int>& nums) {
int x = 0, votes = 0, count = 0;
for(int num : nums)
? ? ? ? {
if(votes == 0) x = num;
votes += num == x ? 1 : -1;
}
for(int num : nums)
if(num == x) count++;
return count > nums.size() / 2 ? x : -1;?
}
};
?
丑數
int n7 = res[a] * 7, n3 = res[b] * 3, n5 = res[c] * 5;
res[i] = min(min(n7, n3), n5);//填最小
if (res[i] == n7) a++; //每種維護自己的下一個
if (res[i] == n3) b++;
if (res[i] == n5) c++;
}
?
lc313
用多個質數,通過維護每個質數的乘積累計索引,逐步生成第n個超級丑數。
class Solution {
typedef long long ll;
public:
int nthSuperUglyNumber(int n, vector<int>& primes)
{
int m=primes.size();
sort(primes.begin(),primes.end());
//memo idx vec
vector<ll> mi(m,0);
vector<ll> res(n,INT_MAX);
res[0] = 1;
for(int i = 1; i < n; i++)?
{
vector<ll> ch(m,0);
for(int j=0;j<m;j++)
{
ch[j]=res[mi[j]]*primes[j];
if(ch[j]<=res[i])
{
res[i]=ch[j];
}
}
for(int j=0;j<m;j++)
{
if(ch[j]==res[i])
mi[j]++;
}
}
return (int)res[n - 1];
}
};
?