Count 1’s in sorted Binary Array

ghz 10months ago ⋅ 149 views

To count the number of 1's in a sorted binary array, you can use a binary search approach to find the index of the first occurrence of 1, and then subtract that index from the length of the array to get the count of 1's. Here's the Java implementation:

public class CountOnes {

    public static int countOnes(int[] nums) {
        int left = 0;
        int right = nums.length - 1;

        // Binary search to find the index of the first occurrence of 1
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == 0) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        // Count of 1's is the difference between the length of the array and the index of the first occurrence of 1
        return nums.length - left;
    }

    public static void main(String[] args) {
        int[] nums = {0, 0, 0, 1, 1, 1, 1};
        int count = countOnes(nums);
        System.out.println("Count of 1's: " + count); // Output: 4
    }
}

In this implementation:

  • We perform a binary search to find the index of the first occurrence of 1 in the sorted binary array.
  • The count of 1's is then computed as the difference between the length of the array and the index of the first occurrence of 1.
  • We test the implementation with an example binary array and print the count of 1's.