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. Yii-数据模型- rules类验证器方法详解

    public function rules(){ return array( array('project_id, type_id, status_id, owner_id, requester_id ...

  2. (转)Android属性设置android:noHistory="true"

    设置 android:noHistory="true"后,该Activity在statck中不留历史痕迹.默认的值是false. 举例说明,假设有三个Activity分别是:A,B ...

  3. 实战Django:官方实例Part4

    上一个part我们创建了投票的内容页,但这个页面仅仅局限于静态展示,投票的"投"字还无从体现.接下来,我们就来看一下,如何把票投起来.   19.创建表单 我们来更新模板文件pol ...

  4. 老工程升级到VS2010或以上时会出现 libc.lib 解决方法

    有些网上的工程都比较老,比如用2003之类.一般会有个静态libc.lib.在新版本里已经没有这个库,被微软无情的抛弃. 编译时会出现动态库找不到: 1>LINK : fatal error L ...

  5. ORA-01207: file is more recent than control file -

    OS: [root@yoon ~]# more /etc/oracle-releaseOracle Linux Server release 5.7 DB: Oracle Database 11g E ...

  6. [转]unzip解压windows zip乱码的处理

    [转]unzip解压windows zip乱码的处理 http://blog.sina.com.cn/s/blog_6c9d65a101012gz0.html 朋友从windows传过来的zip文件, ...

  7. UIAlertView(已经过时) UIActionView swift

    // // ViewController.swift // UILabelTest // // Created by mac on 15/6/23. // Copyright (c) 2015年 fa ...

  8. Java BigDecimal大数字操作

    在java中提供了大数字的操作类,即java.math.BinInteger类和java.math.BigDecimal类.这两个类用于高精度计算,其中BigInteger类是针对大整数的处理类,而B ...

  9. PSP0表格二

    一 项目计划日志 周活动总结表 姓名: 陆宇 日期:2015. 3. 21 日期       任务 听课 编写程序 阅读课本 准备考试 日总计/(min) 周日 60 30 90 周一 300 0 1 ...

  10. 命令学习:iftop

    iftop显示带宽使用情况 http://riobard.com/2010/04/30/l2tp-over-ipsec-ubuntu/ http://jaseywang.me/2011/12/19/i ...