Statistics from a Large Sample

给一个数组, i位上的数n表示n个i, 求min,max,mean, median,mode. 这里只有中位数需要考虑下, 因为数组是频率数组, 所以用两个指针, 辗转相减, 就能找到中间的两个数.

class Solution {
    public double[] sampleStats(int[] count) {
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;
        int maxValue = 0;
        int mode = 0;
        double avg = 0.0;
        int c = 0;
        for(int i = 0; i < count.length; i++) {
            if(count[i] == 0)
                continue;
            min = Math.min(min, i);
            max = Math.max(max, i);
            avg += count[i] * i;
            c += count[i];
            if(maxValue < count[i]){
                maxValue = count[i];
                mode = i;
            }
        }
        avg /= (double)c;
        
        /*median*/
        
        int left = 0;
        int right = count.length - 1;
        while( left < right) {
            if(count[left] == 0) {
                left++;
            } else if(count[right] == 0) {
                right--;
            } else if(count[left] < count[right]) {
                count[right] -= count[left];
                left++;
            } else if(count[left] > count[right]){
                count[left] -= count[right];
                right--; 
            } else {
                left++;
                right--;
            }
        }
            double median = 0.0;
            median = (double)(right + left) / 2.0;
        return new double[]{min, max, avg, median, mode};
    }
}