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

题目描述:

关于一道题的奇淫技巧

代码如下:

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

 

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

 

相关文章:

  • 2021-09-21
  • 2021-10-20
  • 2021-08-21
  • 2022-01-25
  • 2021-07-29
  • 2021-04-13
  • 2021-04-08
  • 2021-10-28
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-06-21
  • 2021-07-15
  • 2022-01-24
  • 2021-07-21
相关资源
相似解决方案