在Array中查找Balanced index Position(s)

时间:2018-03-27 16:07:03

标签: java arrays

给定的数组arr及其大小为 N ,找到平衡指数位置 P ,使得 0到P-1的总和< / strong>数组元素等于 P + 1到N-1 的乘积。

在最坏的情况下,时间复杂度 O(n): 我尝试使用下面的代码,如果Array不包含零,它的工作正常。

/**
* 
*/
package com.array.balance.indexes;
import java.util.HashSet;
import java.util.Set;

/**
* @author Prasad
*
*/
public class FindBalancedIndexesInArray {

public static void main(final String[] args) {
    System.out.println(getIndexes(new int[] { 1, 2, 1, 3 }));
    System.out.println(getIndexes(new int[] { 1, 2, 1 }));
}

private static Set<Integer> getIndexes(final int[] arr) {
    final Set<Integer> indexes = new HashSet<>();
    int leftElementsSum = 0;
    if (arr == null || arr.length == 0) {
        // return Empty set
        return indexes;
    }
    if (arr.length == 1) {
        // If it is Only One Element, previous and next are equal..
        indexes.add(0);
        return indexes;
    }
    /**
     * If the Array doesn't have zero, elements, then Time Complexity is O(n).
     */

    int product = arr[0];
    /**
     * Calculate Product of the array elements
     */
    for (int i = 1; i < arr.length; i++) {
        product *= arr[i];
    }
    /**
     * Time Complexity O(n)
     */
    for (int i = 1; i < arr.length; i++) {
        // Calculate Previous Elements sum
        leftElementsSum += arr[i - 1];
        // calculate Product
        product = product / arr[i];
        // Check Previous Sum and Next Multiplication is Equal..
        if (leftElementsSum == product) {
            indexes.add(i);
        }
    }
    /**
     * For the last element in the array, if the SUM of 0 to N-2 Elements are ZERO,
     * then include last Element Index.
     */
    if (leftElementsSum == 0) {
        indexes.add(arr.length - 1);
    }
    return indexes;
}
}

输出: [2] [1]

注意:数组可以包含实数。

任何人都可以帮助我..! 修改 如果数组的元素为零,则此代码失败。

编辑2:

  1. new int [] {5,0,-5,4} 预期产出:[0,3]
  2. new int [] {5,0--5,4,0,6,4} 预期产出:[0,3,6]

0 个答案:

没有答案