Count the number of occurrences in a sorted array

Given a sorted array arr[] and a number x, write a function that counts the occurrences of x in arr[]. Expected time complexity is O(Logn)

Examples:

  Input: arr[] = {1, 1, 2, 2, 2, 2, 3,},   x = 2
Output: 4 // x (or 2) occurs 4 times in arr[] Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 3
Output: 1 Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 1
Output: 2 Input: arr[] = {1, 1, 2, 2, 2, 2, 3,}, x = 4
Output: -1 // 4 doesn't occur in arr[]

Method 1 (Linear Search)
Linearly search for x, count the occurrences of x and return the count.

Time Complexity: O(n)

Method 2 (Use Binary Search)
1) Use Binary search to get index of the first occurrence of x in arr[]. Let the index of the first occurrence be i.
2) Use Binary search to get index of the last occurrence of x in arr[]. Let the index of the last occurrence be j.
3) Return (j – i + 1);

/* if x is present in arr[] then returns the count of occurrences of x,
otherwise returns -1. */
int count(int arr[], int x, int n)
{
int i; // index of first occurrence of x in arr[0..n-1]
int j; // index of last occurrence of x in arr[0..n-1] /* get the index of first occurrence of x */
i = first(arr, , n-, x, n); /* If x doesn't exist in arr[] then return -1 */
if(i == -)
return i; /* Else get the index of last occurrence of x. Note that we
are only looking in the subarray after first occurrence */
j = last(arr, i, n-, x, n); /* return count */
return j-i+;
} /* if x is present in arr[] then returns the index of FIRST occurrence
of x in arr[0..n-1], otherwise returns -1 */
int first(int arr[], int low, int high, int x, int n)
{
if(high >= low)
{
int mid = (low + high)/; /*low + (high - low)/2;*/
if( ( mid == || x > arr[mid-]) && arr[mid] == x)
return mid;
else if(x > arr[mid])
return first(arr, (mid + ), high, x, n);
else
return first(arr, low, (mid -), x, n);
}
return -;
} /* if x is present in arr[] then returns the index of LAST occurrence
of x in arr[0..n-1], otherwise returns -1 */
int last(int arr[], int low, int high, int x, int n)
{
if(high >= low)
{
int mid = (low + high)/; /*low + (high - low)/2;*/
if( ( mid == n- || x < arr[mid+]) && arr[mid] == x )
return mid;
else if(x < arr[mid])
return last(arr, low, (mid -), x, n);
else
return last(arr, (mid + ), high, x, n);
}
return -;
} /* driver program to test above functions */
int main()
{
int arr[] = {, , , , , , };
int x = ; // Element to be counted in arr[]
int n = sizeof(arr)/sizeof(arr[]);
int c = count(arr, x, n);
printf(" %d occurs %d times ", x, c);
getchar();
return ;
}

Time Complexity: O(Logn)
Programming Paradigm: Divide & Conquer

[geeksforgeeks] Count the number of occurrences in a sorted array的更多相关文章

  1. [Algorithm] Count occurrences of a number in a sorted array with duplicates using Binary Search

    Let's say we are going to find out number of occurrences of a number in a sorted array using binary ...

  2. How to count the number of threads in a process on Linux

    If you want to see the number of threads per process in Linux environments, there are several ways t ...

  3. 2017年上海金马五校程序设计竞赛:Problem C : Count the Number (模拟)

    Description Given n numbers, your task is to insert '+' or '-' in front of each number to construct ...

  4. 【leetcode】1207. Unique Number of Occurrences

    题目如下: Given an array of integers arr, write a function that returns true if and only if the number o ...

  5. 实现一个函数clone,可以对JS中的5种数据类型(Number、String、Object、Array、Boolean)进行值复制

     实现一个函数clone,可以对JS中的5种数据类型(Number.String.Object.Array.Boolean)进行值复制

  6. 实现一个函数clone,使JavaScript中的5种主要的数据类型(包括Number、String、Object、Array、Boolean)进行值复制

    实现一个函数clone,可以对JavaScript中的5种主要的数据类型(包括Number.String.Object.Array.Boolean)进行值复制. 1 /** 对象克隆 2 * 支持基本 ...

  7. Count the number of possible triangles

    From: http://www.geeksforgeeks.org/find-number-of-triangles-possible/ Given an unsorted array of pos ...

  8. OpenCV count the number of connected camera 检测连接的摄像头的数量

    有时候在项目中我们需要检测当前连接在机子上的摄像头的数量,可以通过下面的代码实现,其中连接摄像头的最大数量maxCamNum可以任意修改: /** * Count current camera num ...

  9. 1. 青蛙跳跳FrogJmp Count minimal number of jumps from position X to Y.

    青蛙跳跳: package com.code; public class Test03_1 { public int solution(int X, int Y, int D) { int res = ...

随机推荐

  1. PHP session回收机制

    由于PHP的工作机制,它并没有一个daemon线程,来定时地扫描session信息并判断其是否失效.当一个有效请求发生时,PHP会根据全局变量 session.gc_probability/sessi ...

  2. 点击后弧形展开的炫酷菜单--第三方开源-- CircularFloatingActionMenu(一)

    CircularFloatingActionMenu在github上项目主页地址:https://github.com/oguzbilgener/CircularFloatingActionMenu ...

  3. C# 标准查询表达式

    一.标准查询运算符 1.C#提供了标准查询运算符,例如我想选择专利一系列(pantents)中以年份19开头的专利,可以用如下语句: IEnumerable<Patent> pantent ...

  4. 正整数转换成N进制的数组

    给定一个正整数,按照N进制转换成数组元素存储 //给定一个整数,把它转换成按照N进制存储的数组 #include <stdio.h> #include <stdlib.h> # ...

  5. Python核心编程--学习笔记--7--字典和集合

    本章介绍Python语言中的映射类型(字典)和集合类型,包括操作符.工厂函数.内建函数与方法. 1 字典 字典是Python中唯一的映射类型——键key直接映射到值value.字典是容器类型,其对象是 ...

  6. [.NET] 打造防“狼”神器 :任务栏篇

    @微微一笑:本文标题纯属自娱自乐. 隐藏任务栏效果图: 对比 说起来惭愧,上面这个隐藏任务栏功能,只是完成了我一半的预想.本想是可以选择性的隐藏任务栏上的某个TaskBarButton,但是Win7+ ...

  7. wpf mvvm MenuItem的Command事件

    这是一个事件的辅助类,可以通过它实现MenuItem的Command事件 public class MyCommands : Freezable, ICommand, ICommandSource { ...

  8. Mysql允许外网接入

    首先你可以为mysql创建一个账户,或者为root用户接入数据库. 授权用户指定所有主机以指定用户连接服务器 GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDE ...

  9. 删除undotbs后,数据库无法启动

    SQL> archive log list;Database log mode              No Archive ModeAutomatic archival            ...

  10. 透过数据看现实,漫谈实况FIFA的这些年

    虽然,只是个普通玩家,虽然带了一点青春,一点爱.虽然,有那么些怀念 ~ 好吧,不浪费篇幅伪伪的煽情,直插主题.(很长且多图,更多讲述的是实况FIFA间的你来我往,互相赶超的故事.本想全面展开描述细节, ...