Count frequencies of all elements in array in O(1) extra space and O(n) time

Given an unsorted array of n integers which can contain integers from 1 to n. Some elements can be repeated multiple times and some other elements can be absent from the array. Count frequency of all elements that are present and print the missing elements.

Examples:

Input: arr[] = {2, 3, 3, 2, 5}

Output: Below are frequencies of all elements:

1 -> 0

2 -> 2

3 -> 2

4 -> 0

5 -> 1

Input: arr[] = {4, 4, 4, 4}

Output: Below are frequencies of all elements

1 -> 0

2 -> 0

3 -> 0

4 -> 4

对于统计数字出现频率的题目,最直接的思路就是使用一个hashmap,但是使用hashmap需要用到O(n)的辅助存储空间;同时我们注意到数组中数值的范围是1到n,所以就很容易想到Leetcode中的一道题,First Missing Positive的解题思路:扫描数组,并且把A[i]放到A[A[i]-1]的位置上,但是由于我们需要记录每个数值出现的次数,仅仅这样做是不够的,所以我们决定用A[i]记录数值i+1出现的次数,但是由于要将数值出现的次数与未扫描的数值区分开,所以可以用负数来保存出现的次数。另外一个细节是,假设数组A[i] = k,则应该把k放到A[k-1]的位置上,但是A[k-1]的位置上的数值放到哪里去呢?最开始的处理是继续将A[k-1]中的数字也放到正确的位置上,直到一个轮换周期结束;但是这样的处理增加了程序的复杂度和可读性,容易想不清楚怎么写或者出错,所以一个简单的处理方法就是先把A[k-1]中的数字保存在A[i]中,然后先不要修改i,直到A[i]中的数值为负数或者0为止,所以程序如下:

class solution{

  public void count(int[] A){

    if((A == null)||(A.length == 0)){

      return;

    }

    //preprocess the array, if A[i] == i+1, A[i] = -1; if(A[i] < 1)||(A[i] > A.length) A[i] = 0;

    for(int i=0; i<A.length; i++){

      if(A[i] == (i+1)){

        A[i] = -1;

      } else {

        if((A[i] < 1)||(A[i] > A.length)){

          A[i] = 0;

        }

      }

    }

    int i=0;

    while(i < A.length){

      if(A[i] <= 0){

        i++;

      } else {

        int j = A[i];

        if(A[j-1] <= 0){

          A[i] = 0;

          A[j-1] -= 1;

          i++;

        } else {

          A[i] = A[j-1];

          A[j-1] = -1;

        }

      }

    }

  }

}

时间: 2024-10-20 02:09:25

Count frequencies of all elements in array in O(1) extra space and O(n) time的相关文章

Javacript Remove Elements from Array

參考自: https://love2dev.com/blog/javascript-remove-from-array/ 1. Removing Elements from End of Array var ar = [1, 2, 3, 4, 5, 6]; ar.length = 4; // set length to remove elements console.log( ar ); // [1, 2, 3, 4] var ar = [1, 2, 3, 4, 5, 6]; ar.pop();

max (Largest elements in array)

句法: M = max(A) M = max(A,[],dim) [M,I] = max(___) C = max(A,B) ___ = max(___,nanflag) 描述: M=max(A)返回集合A中最大的元素. 如果A是一个向量,则max(A)返回的是集合A的一个元素. 如果A是一个矩阵,则max(A)返回的是包含每列最大值的行向量. 如果A是一个多维数组,则max(A)沿着第一个数组维度运行,其大小不等于1,将元素作为向量进行处理.该维度变为1,而所有其他维度的大小保持不变.如果A是

Namespace, string, vector and array

1. Headers should not include using declaration Code inside headers ordinarily should not include using declarations. The reason is that the contents of a header are copied into the including program's text. If a header has a using declaration, then

PTA Sort Three Distinct Keys

Suppose you have an array of N elements, containing three distinct keys, "true", "false", and "maybe". Given an O(N)O(N) algorithm to rearrange the list so that all "false" elements precede "maybe" element

[email&#160;protected] Sorting Elements of an Array by Frequency (Sort)

http://www.practice.geeksforgeeks.org/problem-page.php?pid=493 Sorting Elements of an Array by Frequency Given an array of integers, sort the array according to frequency of elements. For example, if the input array is {2, 3, 2, 4, 5, 12, 2, 3, 3, 3,

LeetCode 238 Product of Array Except Self(除自身外数组其余数的乘积)

翻译 给定一个有n个数字的数组nums,其中n大于1,返回一个数组使得output[i]等于除nums[i]外所有元素的乘积. 不用分治并且在O(n)复杂度下解决这个问题. 例如,给定[1, 2, 3, 4],返回[24, 12, 8, 6]. 跟进: 你可以只在常量空间下完成它吗? (备注:在空间复杂度计算时输出数组不作为额外空间.) 原文 Given an array of n integers where n > 1, nums, return an array output such t

26. Remove Duplicates from Sorted Array【easy】

26. Remove Duplicates from Sorted Array[easy] Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with consta

LeetCode 26. Remove Duplicates from Sorted Array

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. For example,Given input array nums 

238. Product of Array Except Self

Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Solve it without division and in O(n). For example, given [1,2,3,4], return [24,12,8,6]. Fo