leetcode18:Excel表列名称(168)、求众数(169)

1.Excel表列名称

给定一个正整数,返回它在 Excel 表中相对应的列名称。

例如,

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 
    ...

思路:相当于26进制转换,只不过有一个坑是1-26,不是0-25。所以为了防止26变成AZ的情况,我们需要在+'Z'后将n减1。

class Solution {
public:
    string convertToTitle(int n) {
        string res;
        int tmp;
        while(n!=0)
        {
            tmp = n % 26;      //取余
            if(tmp == 0)
            {
                res = 'Z' + res;
                n -- ;        //必须减1,因为防止26-》AZ
            }
            else
            {
                res = (char)('A' + tmp -1) + res;
            }
            n = n / 26;       //更新n
        }
        return res;
    }
};

参考链接:https://leetcode-cn.com/problems/excel-sheet-column-title/

2.求众数

给定一个大小为 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。你可以假设数组是非空的,并且给定的数组总是存在众数。

思路:哈希表,利用数组的值作为哈希表的键,用哈希表的值记录数组值出现的次数。如果哈希表存在则值+1,如果不存在则新建键值对。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        map<int,int> m;
        for(int i=0;i<nums.size();i++)
        {
            if(m.count(nums[i])>0)
            {
                m[nums[i]] = m[nums[i]] + 1;        //如果存在这个键,那么对应的值加1
            }
            else
                m[nums[i]] = 1;                     //如果不存在这个键,那么定义新的键,并赋值为1
            if(m[nums[i]] > nums.size() / 2)        //判定当前键出现的次数是否大于n/2
                    return nums[i];
        }
        return -1;
    }
};

参考链接:https://leetcode-cn.com/problems/majority-element/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值