zoukankan      html  css  js  c++  java
  • [LeetCode] 1551. Minimum Operations to Make Array Equal

    You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e. 0 <= i < n).

    In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] (i.e. perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the array equal. It is guaranteed that all the elements of the array can be made equal using some operations.

    Given an integer n, the length of the array. Return the minimum number of operations needed to make all the elements of arr equal.

    Example 1:

    Input: n = 3
    Output: 2
    Explanation: arr = [1, 3, 5]
    First operation choose x = 2 and y = 0, this leads arr to be [2, 3, 4]
    In the second operation choose x = 2 and y = 0 again, thus arr = [3, 3, 3].
    

    Example 2:

    Input: n = 6
    Output: 9

    Constraints:

    • 1 <= n <= 10^4

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

    题意是给一个数字N,代表一个长度为N的数组arr。数组中的数字arr[i] = (2 * i) + 1。一次操作中,你可以选出两个下标,记作 x 和 y ( 0 <= x, y < n )并使 arr[x] 减去 1 、arr[y] 加上 1 (即 arr[x] -=1 且 arr[y] += 1 )。最终的目标是使数组中的所有元素都相等。请问你至少需要几次操作可以将数组中的所有数字相等。

    这道题不难,根据规则发现创建出来的数组长如下这样,是个等差数列。

    index    0  1  2  3  4  5     6    7    8

    num[index]   1  3  5  7  9  11  13  15  17

    既然操作规则会同时涉及到两个数字,那么应该是把数组两边的数字往中间改,或者说改成数组的中位数比较合理。另外需要注意的是

    如果N是奇数,就是直接改成中位数

    如果N是偶数,可以试着将所有数字改成中间两个数的平均值

    时间O(1) - 是有限次数的操作

    空间O(1)

    Java实现

     1 class Solution {
     2     public int minOperations(int n) {
     3         int m = n / 2; 
     4         if (n % 2 == 1) {
     5             return m * (m + 1);
     6         } else {
     7             return m * m;
     8         }
     9     }
    10 }

    LeetCode 题目总结

  • 相关阅读:
    input框限制0开头的数字(0除外)
    圆角头像----CSS3特效
    html中div获取焦点,去掉input div等获取焦点时候的边框
    一些常用的html css整理--文本长度截取
    html5本地存储
    div块级元素获取焦点
    Intellij IDEA 搜索文件内容
    web安全漏洞防护
    Intellij IDEA 自动生成 serialVersionUID
    mysql 年龄计算(根据生日)
  • 原文地址:https://www.cnblogs.com/cnoodle/p/13522066.html
Copyright © 2011-2022 走看看