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. 用FileInputStream读文件,字节数组接收,不知道文件的大小时怎么办

    FileInputStream in = new FileInputStream(文件路径File); byte[] buffer = new byte[in.available()]; in.rea ...

  2. DBGridEh 点击表头排序方法

    方法1: (不用编程写代码) 程序中引用 单元 EhLibCDS设置DBGridEh的属性:      ColumnDefValues.Title.TitleButton = True      Op ...

  3. MySQL线上执行大事务或锁表操作

    前提 在线执行一些大事务或锁表操作(给某个核心级表加一列或者执行修改操作),此时不但主库从库要长时间锁表,主从延迟也会变大.未避免大事务sql对整个集群产生影响,,我们希望一条SQL语句只在Maste ...

  4. iPhone开发中的技巧整理

    1.NSCalendar用法 -(NSString *) getWeek:(NSDate *)d { NSCalendar *calendar = [[NSCalendar alloc] initWi ...

  5. (转)Android网络命令

    转自:http://www.cnblogs.com/shunyao8210/archive/2010/08/10/1796214.html ifconfig 1.       作用 ifconfig用 ...

  6. JavaWeb之 JSP基础

    什么是JSP JSP的全称是java server page, java服务页面.是提供java服务的页面~ 那么和Servlet有什么区别呢?JSP的页面既可以写java代码~也可以写html代码哦 ...

  7. [转]Oracle 10g及pro*c相关问题及解决方法(转)

    Oracle 10g及pro*c相关问题及解决方法 2008年08月21日 星期四 上午 11:21 最近一直在进行ORACLE 10g和PRO*C的学习. 其中遇到了不少的问题: 现列于此,已备他用 ...

  8. Oracle12C的EM无法访问怎么办?

    装完Oracle 12c,想体验下EM Express,缺发现不能用,应该怎么办?12c的EM 不再像以前版本配置那么麻烦,当然提供的功能也没有那么多了,只需要启用对应端口即可,请看:To manua ...

  9. 如何快速重置OUTLOOK2013,2016到初始配置状态,outlook 修改数据文件位置

    适用范围: 安装OUTLOOK的机器 知识点分析: 快速清除当前OUTLOOK所有账户,回归到初始配置状态. 操作步骤: WIN+R调出运行 输入: C:\Program Files (x86)\Mi ...

  10. wifi链接配置

    linux 命令行配置wlan无线网卡 无线网卡配置此页由Linux Wiki日(星期四) 09:28的工作基础上.本文介绍在Linux命令行界面中手动配置无线网卡的方法.目前流行的多数发行版都支持用 ...