LCP 11.期望个数统计(LEETCODE)

LCP 11.期望个数的统计

某互联网公司一年一度的春招开始了,一共有 n 名面试者入选。每名面试者都会提交一份简历,公司会根据提供的简历资料产生一个预估的能力值,数值越大代表越有可能通过面试。

小 A 和小 B 负责审核面试者,他们均有所有面试者的简历,并且将各自根据面试者能力值从大到小的顺序浏览。由于简历事先被打乱过,能力值相同的简历的出现顺序是从它们的全排列中等可能地取一个。现在给定 n 名面试者的能力值 scores,设 X 代表小 A 和小 B 的浏览顺序中出现在同一位置的简历数,求 X 的期望。

提示:离散的非负随机变量的期望计算公式为 。在本题中,由于 X 的取值为 0 到 n 之间,期望计算公式可以是 。

示例 1:

输入:scores = [1,2,3]

输出:3

解释:由于面试者能力值互不相同,小 A 和小 B 的浏览顺序一定是相同的。X的期望是 3 。

示例 2:

输入:scores = [1,1]

输出:1

解释:设两位面试者的编号为 0, 1。由于他们的能力值都是 1,小 A 和小 B 的浏览顺序都为从全排列 [[0,1],[1,0]] 中等可能地取一个。如果小 A 和小 B 的浏览顺序都是 [0,1] 或者 [1,0] ,那么出现在同一位置的简历数为 2 ,否则是 0 。所以 X 的期望是 (2+0+2+0) * 1/4 = 1

示例 3:

输入:scores = [1,1,2]

输出:2

限制:

1 <= scores.length <= 10^5
0 <= scores[i] <= 10^6

//根据数学计算得出要算的期望的值就等于不同的数值的个数
//所以先将数组排序,统计数值种类返回即可
//数学推理如下:
//统计两份各n个文档出现位置相同的期望,相当于吧n个数排列后出现在原位置的期望
//易知总共有n!中排列方式,其中对于这n个数中的单个元素出现在原位置的次数为(n-1)!
//E(x) = (n*(n-1)!) / n! = 1
//所以结果相当于统计出现的数值的种类



#include <iostream>
#include <algorithm>
using namespace std;
int main(){
	int scores[100], n, flag, count;
	cin >> n;
	for(int i = 0; i < n; i ++){
		cin >> scores[i];
	}
	sort(scores, scores+n);
	flag = scores[0];
	count  = 1;
	for(int i = 1; i < n; i ++){
		if(flag != scores[i]){
			count ++;
			flag = scores[i];	
		} 
	}
	cout << count;
	return 0;
} 
class Solution {
public:
    int expectNumber(vector<int>& scores) {
        sort(scores.begin(), scores.end());
        int flag, count;
        flag = scores[0];
        count  = 1;
        for(int i = 1; i < scores.size(); i ++){
            if(flag != scores[i]){
                count ++;
                flag = scores[i];	
            } 
        }
        return count;
    }
};

以下是不同代码表示

class Solution {
public:
    int expectNumber(vector<int>& scores) {
        int n = scores.size(),ans = 0;
        sort(scores.begin(),scores.end());
        for(int i = 0;i < n; i++) if(i == 0 || scores[i] != scores[i-1]) ++ans;
        return ans;
    }
};
//作者:jerry_nju
//来源:力扣(LeetCode)
class Solution {
public:
    int expectNumber(vector<int>& scores) {
        sort(scores.begin(), scores.end());
        return unique(scores.begin(), scores.end()) - scores.begin();
    }
};
//作者:LeetCode-Solution
//来源:力扣(LeetCode)
class Solution {
public:
    int expectNumber(vector<int>& scores) {
        unordered_set<int> set;
        for (int i : scores) set.insert(i);
        return set.size();
    }
};
//作者:OrangeMan
//来源:力扣(LeetCode)
class Solution {
public:
    int expectNumber(vector<int>& scores) {
        //C++STL,实际上就是计算总共有多少个不同的元素,好处是不用排序(因为原数据是无序的),时间复杂度O(nlogn),空间复杂度O(n)
        unordered_set<int> s;
        for(int i:scores)s.insert(i);
        return s.size();
    }
};
//作者:wsxst1234
//来源:力扣(LeetCode)
posted @ 2020-10-27 11:12  Cinxar  阅读(152)  评论(0)    收藏  举报