📜  C++ 程序在已排序的二进制数组中计数 1

📅  最后修改于: 2022-05-13 01:54:20.549000             🧑  作者: Mango

C++ 程序在已排序的二进制数组中计数 1

给定一个按非递增顺序排序的二进制数组,计算其中 1 的个数。

例子:

Input: arr[] = {1, 1, 0, 0, 0, 0, 0}
Output: 2

Input: arr[] = {1, 1, 1, 1, 1, 1, 1}
Output: 7

Input: arr[] = {0, 0, 0, 0, 0, 0, 0}
Output: 0

一个简单的解决方案是线性遍历数组。简单解的时间复杂度为 O(n)。我们可以使用二分搜索在 O(Logn) 时间内找到计数。这个想法是使用二分搜索查找 1 的最后一次出现。一旦我们找到最后一次出现的索引,我们就返回 index + 1 作为计数。
以下是上述思想的实现。

C++
// C++ program to count one’s in a boolean array#include using namespace std;/* Returns counts of 1’s in arr[low..high]. The array isassumed to be sorted in non-increasing order */int countOnes(bool arr[], int low, int high){if (high >= low){// get the middle indexint mid = low + (high – low)/2;// check if the element at middle index is last 1if ( (mid == high || arr[mid+1] == 0) && (arr[mid] == 1))return mid+1;// If element is not last 1, recur for right sideif (arr[mid] == 1)return countOnes(arr, (mid + 1), high);// else recur for left sidereturn countOnes(arr, low, (mid -1));}return 0;}/* Driver Code */int main(){bool arr[] = {1, 1, 1, 1, 0, 0, 0};int n = sizeof(arr)/sizeof(arr[0]);cout << "Count of 1's in given array is " << countOnes(arr, 0, n-1);
return 0;
}[tabbyending]OutputCount of 1's in given array is 4Time complexity of the above solution is O(Logn)Space complexity o(log n) (function call stack)The same approach with iterative solution would be


C++
#include using namespace std;/* Returns counts of 1’s in arr[low..high]. The array isassumed to be sorted in non-increasing order */int countOnes(bool arr[], int n){int ans;int low = 0, high = n – 1;while (low <= high) { // get the middle index
int mid = (low + high) / 2;
// else recur for left side
if (arr[mid] < 1)
high = mid - 1;
// If element is not last 1, recur for right side
else if (arr[mid] > 1)low = mid + 1;else// check if the element at middle index is last 1{if (mid == n – 1 || arr[mid + 1] != 1)return mid + 1;elselow = mid + 1;}}}int main(){bool arr[] = { 1, 1, 1, 1, 0, 0, 0 };int n = sizeof(arr) / sizeof(arr[0]);cout << "Count of 1's in given array is "
<< countOnes(arr, n);
return 0;
}[tabbyending]OutputCount of 1's in given array is 4Time complexity of the above solution is O(Logn)Space complexity is O(1)Please refer complete article on Count 1’s in a sorted binary array for more details!