2023-08-01 Leetcode 2681 英雄的力量

99 阅读1分钟

Problem: 2681. 英雄的力量

思路

首先必须想到的:先排序

解题方法

但是如果遍历左右,还是会超时,因此需要寻找每个求和式子之间的关系

Code


class Solution {
public:
    int sumOfPower(vector<int>& nums) {
        const int MOD = 1e9 + 7;
        sort(nums.begin(), nums.end());
        int ans = 0, s = 0;
        for (long long x : nums) {
            ans = (ans + x * x % MOD * (x + s)) % MOD;
            s = (s * 2 + x) % MOD;
        }
        return ans;
    }
};

参考

leetcode.cn/problems/po…