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];
}
};