zoukankan      html  css  js  c++  java
  • 1558. Minimum Numbers of Function Calls to Make Target Array

    Your task is to form an integer array nums from an initial array of zeros arr that is the same size as nums.

    Return the minimum number of function calls to make nums from arr.

    The answer is guaranteed to fit in a 32-bit signed integer.

    Example 1:

    Input: nums = [1,5]
    Output: 5
    Explanation: Increment by 1 (second element): [0, 0] to get [0, 1] (1 operation).
    Double all the elements: [0, 1] -> [0, 2] -> [0, 4] (2 operations).
    Increment by 1 (both elements)  [0, 4] -> [1, 4] -> [1, 5] (2 operations).
    Total of operations: 1 + 2 + 2 = 5.
    

    Example 2:

    Input: nums = [2,2]
    Output: 3
    Explanation: Increment by 1 (both elements) [0, 0] -> [0, 1] -> [1, 1] (2 operations).
    Double all the elements: [1, 1] -> [2, 2] (1 operation).
    Total of operations: 2 + 1 = 3.
    

    Example 3:

    Input: nums = [4,2,5]
    Output: 6
    Explanation: (initial)[0,0,0] -> [1,0,0] -> [1,0,1] -> [2,0,2] -> [2,1,2] -> [4,2,4] -> [4,2,5](nums).
    

    Example 4:

    Input: nums = [3,2,2,4]
    Output: 7
    

    Example 5:

    Input: nums = [2,4,8,16]
    Output: 8
    

    Constraints:

    • 1 <= nums.length <= 10^5
    • 0 <= nums[i] <= 10^9
    class Solution {
        public int minOperations(int[] nums) {
            int res = 0, n = nums.length;
            while(!allzero(nums)) {
                if(!alleven(nums)) {
                   for(int i = 0; i < n; i++) {
                        if(nums[i] % 2 != 0) {
                            nums[i]--;
                            res++;
                        }
                    } 
                } 
                else {
                    for(int i = 0; i < n; i++) {
                        nums[i] /= 2;
                    }
                    res++;
                }
            }
            return res;
        }
        public boolean allzero(int[] nums) {
            for(int i : nums) {
                if(i != 0) return false;
            }
            return true;
        }
        public boolean alleven(int[] nums) {
            for(int i : nums) {
                if((i & 1) == 1) return false;
            }
            return true;
        }
    }

    我不管,我就要brute force

    只要不是allzero就循环,先判断是否alleven,再进行操作。

  • 相关阅读:
    O052、Create Volume 操作 (Part III)
    O051、Create Volume 操作 (Part II)
    O050、Create Volume 操作 (Part I)
    O049、准备 LVM Volume Provider
    O048、掌握 cinder-scheduler 调度逻辑
    O047、 Cinder 组件详解
    O046、掌握Cinder 的设计思想
    O045、理解 Cinder 架构
    O044、一张图秒懂 Nova 16种操作
    O043、计算节点宕机了怎么办
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13584881.html
Copyright © 2011-2022 走看看