zoukankan      html  css  js  c++  java
  • 805. Split Array With Same Average

    In a given integer array A, we must move every element of A to either list B or list C. (B and C initially start empty.)

    Return true if and only if after such a move, it is possible that the average value of B is equal to the average value of C, and B and C are both non-empty.

    Example :
    Input: 
    [1,2,3,4,5,6,7,8]
    Output: true
    Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.

    Note:

    • The length of A will be in the range [1, 30].
    • A[i] will be in the range of [0, 10000].

    Approach #1: DP. [Java]

    class Solution {
        public boolean splitArraySameAverage(int[] A) {
            int sum = 0;
            for (int num : A) {
                sum += num;
            }
            
            boolean[][] dp = new boolean[sum+1][A.length/2+1];
            dp[0][0] = true;
            
            for (int num : A) {
                for (int i = sum; i >= num; --i) {
                    for (int j = 1; j <= A.length/2; ++j) {
                        dp[i][j] = dp[i][j] || dp[i-num][j-1];
                    }
                }
            }
            
            for (int i = 1; i <= A.length/2; ++i)
                if (sum * i % A.length == 0 && dp[sum * i / A.length][i])
                    return true;
            
            return false;
        }
    }
    

      

    Approach #2: DFS. [Java]

    class Solution {    
        public boolean check(int[] A, int leftSum, int leftNum, int startIndex) {       
            if (leftNum == 0) return leftSum == 0;
            if ((A[startIndex]) > leftSum / leftNum) return false;
            for (int i = startIndex; i < A.length - leftNum + 1; i ++) {
    	    if (i > startIndex && A[i] == A[i - 1]) continue;
                if (check(A, leftSum - A[i], leftNum - 1, i + 1)) return true;
            }
            return false;       
        }
        
        public boolean splitArraySameAverage(int[] A) {
            if (A.length == 1) return false;
            int sumA = 0;
            for (int a: A) sumA += a;
            Arrays.sort(A);
            for (int lenOfB = 1; lenOfB <= A.length / 2; lenOfB ++) {
                if ((sumA * lenOfB) % A.length == 0) {
                    if (check(A, (sumA * lenOfB) / A.length, lenOfB, 0)) return true;
                }
            }
            return false;
            
        }
    }
    

      

    Analysis:

    Can't understanding.

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    linux服务器管理员的12个有用的命令
    登录服务器,首先用到的5个命令
    去掉hive字段中的tab
    html-css实例
    【转】你真的理解Python中MRO算法吗?
    【转】CentOS下expect 安装
    Python|PyCharm安装scrapy包
    Java连接Oracle
    Java连接mysql
    最常用正则表达式
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10883624.html
Copyright © 2011-2022 走看看