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. Oracle中建表空间以及用户

    第一步:创建临时表空间   --创建临时表空间-- CREATE TEMPORARY TABLESPACE JSYCCS_TEMP ---'JSYCCS_TEMP'临时表空间名 TEMPFILE 'E ...

  2. MapReduce shuffle阶段详解

    在Mapreduce中,Shuffle过程是Mapreduce的核心,它分布在Mapreduce的map阶段和reduce阶段,共可分为6个详细的阶段: 1).Collect阶段:将MapTask的结 ...

  3. 十天学会单片机Day1点亮数码管(数码管、外部中断、定时器中断)

    1.引脚定义 P3口各引脚第二功能定义 标号 引脚 第二功能 说明 P3.0 10 RXD 串行输入口 P3.1 11 TXD 串行输出口 P3.2 12 INT0(上划线) 外部中断0 P3.3 1 ...

  4. DoubanFm之设计模式(一)

    前两版DoubanFm写的太戳,第一版可以忽略,当是熟悉WP手机的一些API.. 第二版用了比较多的依赖注入,熟悉了Messenger,过后越写越大,感觉不对,赶快打住..现在开始好好思考各模块了. ...

  5. linux C socket

    socket套接字和管道同样可以提供进程内通信.但套接字更胜一筹,不同的进程可以跨越不同的主机(说白了,支持网络通信).使用套接字的知名程序:telnet.rlogin.ftp等. 你需要知道的一些基 ...

  6. poj 1564 Sum It Up

    题目连接 http://poj.org/problem?id=1564 Sum It Up Description Given a specified total t and a list of n ...

  7. Tutorial: Analyzing sales data from Excel and an OData feed

    With Power BI Desktop, you can connect to all sorts of different data sources, then combine and shap ...

  8. Oracle 11gR2 Database和Active Data Guard迁移案例

    客户一套核心系统由一台Oracle Database 11.2.0.3.4单机和一台Active Data Guard组成,分别运行在两台PC服务器上,Oracle Linux 5.8 x86_64b ...

  9. iOS学习之C语言指针

     访问数据的两种方式: 1.直接访问: 2.间接访问:先找到内存地址,根据地址访问存储单元.(内存地址 被称为指针) 定义指针变量: 类型修饰符 *指针变量名 = NULL; NULL表示空指针,相当 ...

  10. iis7应用程序池自动关闭问题解决

    解决: 应用程序池启动32位应用程序 设置托管管道为集成 (仍然有问题) 图片:123.png 访问网站之前 应用程序池是开启的 访问后 网页报503 service unavailable应用程序池 ...