[LeetCode 169,171][简单]多数元素/Excel表列序号

169.多数元素
题目链接
比较显然的做法是排个序后取中间元素和哈希表
看了下题解发现最后一个方法比较巧妙,叫做Boyer-Moore 投票算法,就是先把第一个元素设置为候选,然后循环过程中对候选+1,非候选 -1,到零后把下一个元素置为候选,最后的候选就是真值,简单证明下:

  • 候选为真,则最多删掉同样数量的候选与非候选
  • 候选为假
    • 删掉更多的非候选,对结果无影响
    • 删掉同样多的非候选与候选
  • 真值过半,所以假候选一定留不到最后。
class Solution {
public:
    int majorityElement(vector<int>& nums) {
        int flag = 0,ans = 0;
        for (auto i : nums){
            if(!flag){
                ans = i;
                flag++;
            }
            else if (ans == i)flag++;
            else flag--;
        }
        return ans;
    }
};

171.Excel表列序号
题目链接

class Solution {
public:
    int titleToNumber(string s) {
        int ans = 0;
        for(int i=0,len = s.size();i<len; i++){
            ans *= 26;
            ans += s[i]-'A'+1;
        }
        return ans;
    }
};
发布了104 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/IDrandom/article/details/104209782