关于一道题的奇淫技巧

题目链接:https://www.nowcoder.com/practice/e8a1b01a2df14cb2b228b30ee6a92163?tpId=13&tqId=11181&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

题目描述:

关于一道题的奇淫技巧_第1张图片

代码如下:

class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int> numbers) {
        int n = numbers.size();
        if (n == 0) return 0;
         
        int num = numbers[0], count = 1;
        for (int i = 1; i < n; i++) {
            if (numbers[i] == num) count++;
            else count--;
            if (count == 0) {
                num = numbers[i];
                count = 1;
            }
        }
        // Verifying
        count = 0;
        for (int i = 0; i < n; i++) {
            if (numbers[i] == num) count++;
        }
        if (count * 2 > n) return num;
        return 0;
    }
};

 

前两次心中推算,总以为此代码出了差错,后来细想不觉惊叹作者的奇淫技巧,实在巧妙!完美地运用了“超过数组长度的一半”这个临界条件;

 

转载于:https://www.cnblogs.com/zf-blog/p/9911641.html

你可能感兴趣的:(关于一道题的奇淫技巧)