LeetCode第376场周赛

文章目录

    • 1.Find Missing and Repeated Values
    • 2.Divide Array Into Arrays With Max Difference
    • 3.Minimum Cost to Make Array Equalindromic

1.Find Missing and Repeated Values

直接暴力过

class Solution {
public:
    vector<int> findMissingAndRepeatedValues(vector<vector<int>>& grid) {
        vector<int> res(2,0);
        int n = grid.size();
        unordered_map<int,int> map;
        for(int i = 0;i < n;i++){
            for(int j = 0;j < n;j++) map[grid[i][j]]++;
        }
        for(int i = 1;i <= pow(n,2);i++){
            if(map[i] == 2) res[0] = i;
            if(map[i] == 0) res[1] = i;
        }
        return res;
    }
};

2.Divide Array Into Arrays With Max Difference

排序+判断

class Solution {
public:
    vector<vector<int>> divideArray(vector<int>& nums, int k) {
        int n = nums.size();
        sort(nums.begin(),nums.end());
        vector<vector<int>> res;
        for(int i = 0;i < n - 2;i+=3){
            if(nums[i+1] - nums[i] > k || nums[i+2] - nums[i] > k || nums[i+2] - nums[i] > k) return res;
        }
        for(int i = 0;i < n - 2;i+=3){
            vector<int> tmp;
            for(int j = i;j < i + 3;j++){
                tmp.push_back(nums[j]);
            }
            res.push_back(tmp);
        }
        return res;
    }
};

3.Minimum Cost to Make Array Equalindromic

中位数贪心+寻找左右最近回文数

class Solution {
public:
    vector<int> nearestPalindrome(int x){
        string s = to_string(x);
        if(s == string(s.rbegin(),s.rend())) return {x,x};
        int r = x;
        while(r++){
            string tmpStr = to_string(r);
            if(tmpStr == string(tmpStr.rbegin(),tmpStr.rend())) break;
        }
        int l = x;
        while(l--){
            string tmpStr = to_string(l);
            if(tmpStr == string(tmpStr.rbegin(),tmpStr.rend())) break;
        }
        return {l,r};
    }
    long long minimumCost(vector<int>& nums) {
        long long res1 = 0;
        long long res2 = 0;
        double sum = 0;
        int n = nums.size();
        sort(nums.begin(),nums.end());
        int midNum = 0;
        if(n % 2 == 1) midNum = nums[n/2];
        else midNum = (nums[n/2] + nums[n/2-1]) / 2;
        vector<int> paliNum = nearestPalindrome(midNum);
        for(auto x:nums){
            res1 += abs(x-paliNum[0]);
        }
        for(auto x:nums){
            res2 += abs(x-paliNum[1]);
        }
        return min(res1,res2);
    }
};

你可能感兴趣的:(leetcode,算法,数据结构,c++)