Leetcode 453. 最小操作次数使数组元素相等

原题链接:Leetcode 453. minimum moves to equal array elements

Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.

In one move, you can increment n - 1 elements of the array by 1.

Example 1:

bash 复制代码
Input: nums = [1,2,3]
Output: 3

Explanation: Only three moves are needed (remember each move increments two elements):

1,2,3\] =\> \[2,3,3\] =\> \[3,4,3\] =\> \[4,4,4

Example 2:

bash 复制代码
Input: nums = [1,1,1]
Output: 0

Constraints:

  • n == nums.length
  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109
  • The answer is guaranteed to fit in a 32-bit integer.

题目大意:

给了一个长度为n的数组 nums ,每次操作能使其中的n-1个元素加1,问做多需要多少次数能够使得所有元素相等

方法一:模拟

思路:

转换思路:每次使得n-1个元素加1,等效为使得一个元素减1

那么只要找到值最小的元素,合计一下其他元素减到最小值的步骤总和即可。

需要的操作次数和题目要求在值上是相等的。

C++ 代码:

cpp 复制代码
class Solution {
public:
    int minMoves(vector<int>& nums) {
        // 找到数组中最小值
        int min_ = *min_element(nums.begin(), nums.end());
        int ans = 0;

        for(auto num : nums){
            ans += num - min_;
        }

        return ans;
    }
};

复杂度分析:

  • 时间复杂度:O(n),先找出最小值,然后遍历一遍合计次数
  • 空间复杂度:O(1)

补充:C++求vector容器中的最大值(最小值)及其位置

cpp 复制代码
#include <vector>
#include <algorithm>

vector<int> a = {2, 4, 6, 7, 1, 0, 8, 9, 5, 3};

// 最大值最小值的位置
auto max_pos = max_element(a.begin(), a.end());
auto min_pos = min_element(a.begin(), a.end());

// 最大值和最小值
int max_val = *max_element(a.begin(), a.end());
int min_val = *min_element(a.begin(), a.end());

也可以用于求普通数组:

cpp 复制代码
int a[] = {1, 2, 3, 4, 5, 6};
int max_val = *max_element(a, a+6);
int min_val = *min_element(a, a+6);
相关推荐
想进个大厂3 小时前
代码随想录day31 贪心05
数据结构·算法·leetcode
橘颂TA3 小时前
【剑斩OFFER】算法的暴力美学——力扣 207 题:课程表
数据结构·c++·算法·leetcode·职场和发展
有一个好名字3 小时前
力扣-迷宫中离入口最近的出口
算法·leetcode·职场和发展
踩坑记录3 小时前
leetcode hot100 226. 翻转二叉树 easy 递归 层序遍历 BFS
算法·leetcode·宽度优先
鱼跃鹰飞4 小时前
Leetcode会员尊享面试100题:333.最大二叉搜索子树
数据结构·算法·leetcode·面试
鱼跃鹰飞4 小时前
Leetcode会员尊享面试100题:255.验证二叉搜索树的前序遍历序列
算法·leetcode·面试
YuTaoShao4 小时前
【LeetCode 每日一题】744. 寻找比目标字母大的最小字母——(解法一)遍历
算法·leetcode·职场和发展
im_AMBER4 小时前
Leetcode 110 奇偶链表
数据结构·学习·算法·leetcode
踩坑记录6 小时前
leetcode hot100 easy 101. 对称二叉树 递归 层序遍历 bfs
算法·leetcode·宽度优先
老鼠只爱大米7 小时前
LeetCode经典算法面试题 #98:验证二叉搜索树(递归法、迭代法等五种实现方案详解)
算法·leetcode·二叉树·递归·二叉搜索树·迭代