leetcode--寻找规律题,统计总数之类题目--待更

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值