zoukankan      html  css  js  c++  java
  • [LeetCode] 462. Minimum Moves to Equal Array Elements II

    Given a non-empty integer array, find the minimum number of moves required to make all array elements equal, where a move is incrementing a selected element by 1 or decrementing a selected element by 1.

    You may assume the array's length is at most 10,000.

    Example:

    Input:
    [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]

    这题就是在453基础上多了个+操作,思路大体是一样的,那个是减到最小那个数,
    因为可以有两个操作,我们就全部都操作到中位数就行了
    class Solution {
        public int minMoves2(int[] nums) {
            int sum = 0;
            Arrays.sort(nums);
            int temp = nums[nums.length / 2];
            for (int i = 0; i < nums.length; i++) {
                if (i < nums.length / 2)
                    sum += temp - nums[i];
                else 
                    sum += nums[i] - temp;
            }
            return sum;
        }
    }
  • 相关阅读:
    bp算法原理
    bp算法
    Python之简单的神经网络
    人工智能教程
    clickhouse的windowFunnel(漏斗)
    Hihocoder 1079 离散化
    Hihocoder 1063 缩地
    md5
    搜索引擎 中文分词
    Hihocoder 1059 String Matching Content Length
  • 原文地址:https://www.cnblogs.com/Moriarty-cx/p/9769739.html
Copyright © 2011-2022 走看看