時間複雜度爲 \(O(n)\) 的算法,順序遍歷數組,當該數字第一次出現時開始記錄次數。算法
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { int n = data.size(); if (n == 0) return 0; int num = 0; for (int i = 0; i < n; i++) { if (data[i] == k) { num = 1; while (i + 1 < n && data[i+1] == k) { num++; i++; } break; } } return num; } };
時間複雜度爲 \(O(logn)\) 的算法,藉助二分查找,分別查找該數字第一次在數組中出現的位置和最後一次在數組中出現的位置,而後便可獲得 出現的次數。數組
class Solution { public: int GetNumberOfK(vector<int> data ,int k) { int n = data.size(); if (n == 0) return 0; int num = 0; int i = Find_First_K(data, k); int j = Find_Last_K(data, k); num = (i == -1) ? 0 : (j - i + 1); return num; } int Find_First_K(vector<int> &data, int k) { int left = 0; int right = data.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; if (data[mid] == k) { // 到數組頭了或者前一個元素不爲 k if (mid == 0 || data[mid-1] != k) return mid; else right = mid - 1; } else if (data[mid] > k) right = mid - 1; else left = mid + 1; } return -1; } int Find_Last_K(vector<int> &data, int k) { int left = 0; int right = data.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; if (data[mid] == k) { // 到數組尾了或者後一個元素不爲 k if (mid == data.size() - 1 || data[mid+1] != k) return mid; else left = mid + 1; } else if (data[mid] > k) right = mid - 1; else left = mid + 1; } return -1; } };
獲取更多精彩,請關注「seniusen」!spa