1. 程式人生 > >劍指Offer - 判斷數組中是否有一個數出現次數多於一半

劍指Offer - 判斷數組中是否有一個數出現次數多於一半

div amp 的確 出現 question https 一個數 subject scribe

https://www.nowcoder.net/practice/e8a1b01a2df14cb2b228b30ee6a92163?tpId=13&tqId=11181&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

題目描述

數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。例如輸入一個長度為9的數組{1,2,3,2,2,2,5,4,2}。由於數字2在數組中出現了5次,超過數組長度的一半,因此輸出2。如果不存在則輸出0。

思路:

勉強做出來了,但是最後一步還是參考了別人的。就是關於怎麽檢驗這個數字出現的次數的確是超過了一半,而不是沒有解的結果,我沒有什麽思路。看了別人的。 別人有好幾種解法,我覺得partition的思路還是很不錯的。 那麽我自己,其實用的是消去法。能解出結果,不過最後是需要再O(n)檢查一下這個結果的確合法。

我的代碼如下:

class Solution {
public:
    int MoreThanHalfNum_Solution(vector<int> xx) {
        vector<int> numbers = xx;
        int n = numbers.size();
        while (n > 1) {
            int y = 0;
            for (int x = 0; x < n/2; ++x) {
                if (numbers[2*x] == numbers[2*x+1
]) { numbers[y++] = numbers[2*x]; } } if (n == n/2*2+1) { numbers[y++] = numbers[n-1]; } n = y; } int cnt = 0; for (int i=0; i<xx.size(); ++i) { if (xx[i] == numbers[0
]) cnt++; } if (cnt > xx.size() / 2) return numbers[0]; else return 0; } };

劍指Offer - 判斷數組中是否有一個數出現次數多於一半