1-劍指offer: 數組中出現次數超過一半的數字
阿新 • • 發佈:2019-05-14
vector 兩個 dex 如果 num 輸入 index 不存在 lse
題目描述
數組中有一個數字出現的次數超過數組長度的一半,請找出這個數字。例如輸入一個長度為9的數組{1,2,3,2,2,2,5,4,2}。由於數字2在數組中出現了5次,超過數組長度的一半,因此輸出2。如果不存在則輸出0。
代碼:
// 至少三種方法 // 1. 遍歷統計每個數字次數(O(n^2)) // 2. 借助快排思想(O(n)) // 3. 設置兩個標誌位,一個用於記錄當前數字,另一個用於計數:向後遍歷,當遇到相同的數字時,計數加1; // 當遇到不同的數字時,計數減一;並且當計數為0時,替換為當前數字,計數置為1,繼續往後遍歷,直到數組最後.(O(n)) // class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { if (numbers.size() == 0) return 0; int current_num = numbers[0]; int cnt = 1; for (std::string::size_type index = 1; index < numbers.size(); index++) { if (numbers[index] == current_num) { cnt++; } else { cnt--; if (!cnt) { if (index == numbers.size()-1) return 0; current_num = numbers[index]; cnt = 1; } } } return current_num; } };
需要註意容易犯錯的地方在於如果最後不做檢查,很容易導致最後返回的是最後的值,而不會返回0.
1-劍指offer: 數組中出現次數超過一半的數字