当前位置: 代码迷 >> 综合 >> 2022.04.10LeetCode周赛
  详细解决方案

2022.04.10LeetCode周赛

热度:44   发布时间:2023-11-15 21:20:06.0

周赛

第一题:

class Solution {
    
public:int largestInteger(int num) {
    auto s = std::to_string(num);for (int i = 0; i < int(s.length()); i++) {
    for (int j = 0; j < int(s.length()); j++) {
    if (s[i] % 2 == s[j] % 2 && s[i] > s[j]) {
    std::swap(s[i], s[j]);}}}return std::atoi(s.c_str());}
};

第三题

constexpr int P = 1000000007;
class Solution {
    
public:int maximumProduct(vector<int>& a, int k) {
    int n = a.size();std::priority_queue<std::pair<int, int>> h;for (int i = 0; i < n; i++) {
    h.emplace(-a[i], i);}while (k--) {
    auto [x, i] = h.top();h.pop();a[i]++;h.emplace(-a[i], i);}int ans = 1;for (int i = 0; i < n; i++) {
    ans = 1LL * ans * a[i] % P;}return ans;}
};

直接用小根堆就可以AC(一开始还用了sort 直接超时。。。)

class Solution {
    
public:int maximumProduct(vector<int>& nums, int k) {
    if(nums.size() == 0) return 0;if(nums.size() == 1) return nums[0] + k; priority_queue<int, vector<int>, greater<int> > p;for(int i =  0; i < nums.size(); ++i){
    p.emplace(nums[i]);}for(int i = 0; i <k; i++){
    // if(nums[0] > nums[1]){
    // i--;// sort(nums.begin(), nums.end());// }// else nums[0] = nums[0] + 1;int minNum = p.top();p.pop();minNum += 1;p.emplace(minNum);}const long long int mod = 1e9 + 7;int res  =1;// for(auto num: p){
    // res = (res % mod *num) % mod;// }while(!p.empty()){
    int minNum = p.top();p.pop();res = (res % mod *minNum) % mod;}return res;}
};