Leetcode 453. Minimum Moves to Equal Array Elements
題目的意思是給定一個長度為n的非空陣列,每次使其中的n-1個數加1,問最少操作多少次可以使陣列中的所有數字相等。
思路:我們可以採用逆向思維,因為題目只要求最後使陣列中所有數字相等,並沒有說等於多少。所以每次使其中n-1個數加1,就相當於每次使陣列中的一個數減1:先找到陣列中最小的數字,然後遍歷陣列所有元素,每個數與最小數字差值之和即為所求。
class Solution {
public:
int minMoves(vector<int>& nums) {
int minimum=INT_MAX, re=0;
for(int x:nums)
minimum=min(x,minimum);
for(int x:nums)
re+=x-minimum;
return re;
}
};
相關文章
- 【Leetcode】453. Minimum Moves to Equal Array ElementsLeetCode
- Minimum Moves to Equal Array Elements 最小移動次數使陣列元素相等陣列
- LeetCode | 153. Find Minimum in Rotated Sorted ArrayLeetCode
- LeetCode C++ 1464. Maximum Product of Two Elements in an Array【Array/Sort】簡單LeetCodeC++
- [LeetCode] 2684. Maximum Number of Moves in a GridLeetCode
- Find Minimum in Rotated Sorted Array I & II
- [LeetCode] 727. Minimum Window SubsequenceLeetCode
- [LeetCode] 2831. Find the Longest Equal SubarrayLeetCode
- [LeetCode] 416. Partition Equal Subset SumLeetCode
- Leetcode Sort ArrayLeetCode
- LeetCode 209. Minimum Size Subarray Sum ?LeetCode
- Leetcode 209. Minimum Size Subarray SumLeetCode
- LeetCode のminimum-depth-of-binary-treeLeetCode
- [LeetCode] 2491. Divide Players Into Teams of Equal SkillLeetCodeIDE
- Rotate Array@LeetCodeLeetCode
- [LeetCode] 2406. Divide Intervals Into Minimum Number of GroupsLeetCodeIDE
- [LeetCode] 3096. Minimum Levels to Gain More PointsLeetCodeAI
- [LeetCode] 857. Minimum Cost to Hire K WorkersLeetCode
- [LeetCode] 671. Second Minimum Node In a Binary TreeLeetCode
- [leetcode] 1624. Largest Substring Between Two Equal CharactersLeetCode
- Leetcode 347. Top K Frequent ElementsLeetCode
- Leetcode 203. Remove Linked List ElementsLeetCodeREM
- LeetCode | 203. Remove Linked List ElementsLeetCodeREM
- LeetCode Patching Array All In OneLeetCode
- LeetCode Kth Largest Element in an ArrayLeetCode
- [LeetCode] 3226. Number of Bit Changes to Make Two Integers EqualLeetCode
- LeetCode 1305 All Elements in Two Binary Search TreesLeetCode
- [LeetCode] 1750. Minimum Length of String After Deleting Similar EndsLeetCodeMILA
- LeetCode 452. Minimum Number of Arrows to Burst Balloons Sort/MediumLeetCode
- [LeetCode] 3152. Special Array IILeetCode
- Leetcode 88. Merge Sorted ArrayLeetCode
- Leetcode 33 Search in Rotated Sorted ArrayLeetCode
- LeetCode之Squares of a Sorted Array(Kotlin)LeetCodeKotlin
- LeetCode之Sort Array By Parity(Kotlin)LeetCodeKotlin
- [LeetCode] 3239. Minimum Number of Flips to Make Binary Grid Palindromic ILeetCode
- [LeetCode] 3011. Find if Array Can Be SortedLeetCode
- [LeetCode] 238. Product of Array Except SelfLeetCode
- [leetcode] 1394. Find Lucky Integer in an ArrayLeetCode
- Leetcode 26 Remove Duplicates from Sorted ArrayLeetCodeREM