搜狗笔试总结

  1. 看不懂答案。。。尴尬
image.png
  1. 求方差和最小的idx。方法就是D(x) = E(X^2) - E(X)2,利用前缀和数组,可以很快计算出arr[i:j]的E(X)2和E(X^2).
class Solution:
    def find_best_cut(self , arr):
        # write code here
        n = len(arr)
        prex = [0]
        prex2 = [0]
        for num in arr:
            prex.append(prex[-1]+num)
            prex2.append(prex2[-1]+num**2)
        def var(i,j):
            if i>=j:return 0
            n = j-i+1
            Ex = (prex[j+1]-prex[i])/n
            Ex2 = (prex2[j+1]-prex2[i])/n
            return Ex2-Ex**2
        v = float('inf')
        res = 0
        for i in range(0,n):
            temp = abs(var(0,i-1) + var(i,n-1))
            if temp < v:
                res = i
                v = temp
        return res

参考资料:
https://blog.csdn.net/weixin_41896265/article/details/108424304

你可能感兴趣的:(搜狗笔试总结)