原文:

给定一个数组 a[],数组的大小是 n,另一个是 key k,任务是找出 key k 出现在数组中的概率。 例:

input : n = 6
        a[] = { 4, 7, 2, 0, 8, 7, 5 }
        k = 3
output :0
since value of k = 3  is not present in array,
hence the probability of 0.
input :n = 10
       a[] = { 2, 3, 5, 1, 9, 8, 0, 7, 6, 5 }
       k = 5
output :0.2

的概率可以用下面的公式求出:

probability = total number of k present /
                          size of array.

首先计算 k 的数量,然后概率将是 k 的数量除以 n,即 count/n 下面是上述方法的实现:

c

// c   code to find the probability of
// search key k present in array
#include 
using namespace std;
// function to find the probability
float kpresentprobability(int a[], int n, int k)
{
    float count = 0;
    for (int i = 0; i < n; i  )
        if (a[i] == k)
            count  ;
    // find probability
    return count / n;
}
// driver code
int main()
{
    int a[] = { 4, 7, 2, 0, 8, 7, 5 };
    int k = 3;
    int n = sizeof(a) / sizeof(a[0]);
    cout << kpresentprobability(a, n, k);
    return 0;
}

python 3

# python3 code to find the
# probability of search key
# k present in 1d-array (list).
# function to find the probability
def kpresentprobability(a, n, k) :
    count = a.count(k)
    # find probability upto
    # 2 decimal places
    return round(count / n , 2)
# driver code
if __name__ == "__main__" :
    a = [ 4, 7, 2, 0, 8, 7, 5 ]
    k = 2
    n = len(a)
    print(kpresentprobability( a, n, k))
# this code is contributed
# by ankitrai1

java 语言(一种计算机语言,尤用于创建网站)

// java code to find the probability
// of search key k present in array
class gfg
{
// function to find the probability
static float kpresentprobability(int a[],
                                 int n,
                                 int k)
{
    float count = 0;
    for (int i = 0; i < n; i  )
        if (a[i] == k)
            count  ;
    // find probability
    return count/ n;
}
// driver code
public static void main(string[] args)
{
    int a[] = { 4, 7, 2, 0, 8, 7, 5 };
    int k = 2;
    int n = a.length;
    double n = kpresentprobability(a, n, k);
    double p = (double)math.round(n * 100) / 100;
    system.out.println(p);
}
}
// this code is contributed
// by chitranayal

c

// c# code to find the probability
// of search key k present in array
using system;
class gfg
{
// function to find the probability
static float kpresentprobability(int[] a,
                                 int n,
                                 int k)
{
    float count = 0;
    for (int i = 0; i < n; i  )
        if (a[i] == k)
            count  ;
    // find probability
    return count/ n;
}
// driver code
public static void main()
{
    int[] a = { 4, 7, 2, 0, 8, 7, 5 };
    int k = 2;
    int n = a.length;
    double n = kpresentprobability(a, n, k);
    double p = (double)math.round(n * 100) / 100;
    console.write(p);
}
}
// this code is contributed
// by chitranayal

服务器端编程语言(professional hypertext preprocessor 的缩写)


java 描述语言


output

0

时间复杂度:o(n)