1. #621 task-scheduler
官网网上提供的解决方案: https://leetcode.com/problems/task-scheduler/#/solution
理解方案:类似打印机问题,容量为n,相同任务之间的间隔也为n
1)先统计每个任务的数量m[i], 统计相同任务数量最大为count
2)ans=(count-1)*(n+1),每两个相同的任务之间间隔n+1个任务,共有(count-1)个这样的间隔
3)有相同的最大的count值的char值之间还会存在一个间隔,所有当任务的数量==count时,ans++。
4) return max(ans,tasks.size())如果任务数大于上面的ans,说明此时任务的安排可之间安排,不存在上述的冲突情况,直接取任务数
实现:
class Solution {
public:
int leastInterval(vector<char>& tasks, int n) {
map<char,int>m;
int count=0;
for(char c:tasks)
{
m[c]++;
count=max(count,m[c]);
}
int ans=(count-1)*(n+1);
for(auto p:m)
{
if(p.second==count)
ans++;
}
return max((int)tasks.size(),ans);
}
};
2.#461 Hamming Distance
统计1的个数,将两个数先异或^,再统计1的个数
class Solution {
public:
int hammingDistance(int x, int y) {
int temp=x^y;
int count=0;
while(temp)
{
++count;
temp&=temp-1;
}
return count;
}
};
3.#561 Array Partition I
分成n组,先排序,0,2,4等双数位的数字相加为结果,这里注意javascript排序注意为数字排序
function cmp(x,y)
{
return x-y;
}
var arrayPairSum = function(nums) {
nums.sort(cmp);
var sum=0;
for(var i=0;i<nums.length;++i){
if(i%2==0)
sum=sum+nums[i];
}
return sum;
};