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 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ 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;
}
};