LeetCode5488. 使数组中所有元素相等的最小操作数

class Solution {
     
public:
    int minOperations(int n) {
     

        vector<int> a;
        for (int i = 0;i < n;i++)
        {
     
            a.push_back(2 * i + 1);
        }

        if (n % 2 == 1)
        {
     
            int mid = a[n / 2];

            int ans = 0;
            for (int i = 0;i < n / 2;i++)
            {
     
                ans += mid - a[i];
            }
            return ans;
        }
        if (n % 2 == 0)
        {
     
            int mid = (a[n / 2] + a[n / 2 - 1]) / 2;

            int ans = 0;
            for (int i = 0;i < n/2;i++)
            {
     
                ans += mid - a[i];
            }
            return ans;
        }
        return -1;
    }
};

你可能感兴趣的:(算法)