• 0462. Minimum Moves to Equal Array Elements II (M)


    Minimum Moves to Equal Array Elements II (M)

    题目

    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 or decrement an element of the array by 1.

    Example 1:

    Input: nums = [1,2,3]
    Output: 2
    Explanation:
    Only two moves are needed (remember each move increments or decrements one element):
    [1,2,3]  =>  [2,2,3]  =>  [2,2,2]
    

    Example 2:

    Input: nums = [1,10,2,9]
    Output: 16 
    

    Constraints:

    • n == nums.length
    • 1 <= nums.length <= 10^5
    • -109 <= nums[i] <= 10^9

    题意

    给定一个数组,每次可以对其中一个元素进行+1或-1,问最少需要几步能将所有元素变为一样。

    思路

    找到中位数,将所有元素变为中位数所需要的步数就是最少步数。其中的原理可以参考Leetcode 462. Minimum Moves to Equal Array Elements II(L1范数性质)


    代码实现

    Java

    class Solution {
        public int minMoves2(int[] nums) {
            int ans = 0;
            Arrays.sort(nums);
            int mid = (nums[(nums.length - 1) / 2] + nums[nums.length / 2]) / 2;
            
            for (int num : nums) {
                ans += Math.abs(num - mid);
            }
            
            return ans;
        }
    }
    
  • 相关阅读:
    java代码块执行顺序
    Oracle-SQL高级查询
    java单例模式
    Oracle序列和伪表
    Oracle函数
    Oracle存储过程
    Oracle触发器
    Oracle分析函数
    Oracle分页查询
    Oracle联合查询
  • 原文地址:https://www.cnblogs.com/mapoos/p/14787966.html
Copyright © 2020-2023  润新知