[英]Check if sum of left side of array equal to right side of array in o(n)
I was given an array of numbers (integer) and I need to return the element if the sum of numbers in his right side equals to the sum of numbers in his left size in o(n).我得到了一个数字数组(整数),如果他右侧的数字总和等于 o(n) 中左侧数字的总和,我需要返回该元素。
For example the array {1,2,2,9,3,2} the program should print 9 because 1+2+2 = 5 and 3+2=5例如数组 {1,2,2,9,3,2} 程序应该打印 9 因为 1+2+2 = 5 和 3+2=5
I attached my code but it's not o(n) complexity.我附上了我的代码,但它不是 o(n) 复杂性。 appreciate your help.感谢您的帮助。
Thanks.谢谢。
public class Program {
public static void checkIfEqualOption1(int[] arr){
int sumRight = 0;
int sumLeft=0;
//sumRight+=numbers[0];
for (int i=0; i < arr.length; i++){
if (i>0){
sumRight+=arr[i-1];
for (int j=i+1; j<arr.length; j++){
sumLeft+=arr[j];
}
if (sumRight==sumLeft){
System.out.println("\nFound = "+arr[i]);
break;
}
}
}
}
public static void print(int[] arr){
for (int i=0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hi");
int[] numbers = {1,2,2,9,3,2};
System.out.println("Array numbers:");
for (int i=0; i < numbers.length; i++){
System.out.print(numbers[i] + " ");
}
System.out.println("\n");
checkIfEqualOption1(numbers);
}
}
Start with the observation that for each i
从观察开始,对于每个i
arraySum(0, i) + arraySum(i+1, n) == arrayTotal
so所以
arraySum(i+1, n) == arrayTotal - arraySum(0, i);
^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
Sum on the right Sum on the left
Compute the arrayTotal
in the first pass;在arrayTotal
计算arrayTotal
; then walk the array from the left, computing the partial sum.然后从左边遍历数组,计算部分和。 Stop once you reach a position where到达某个位置后停止
partialSum == arrayTotal - partialSum
This should work in O(n)
, you don't need to sort the array:这应该在O(n)
,您不需要对数组进行排序:
public class Program {
public static void checkIfEqualOption1(int[] arr){
int sumTotal=0;
for (int i=0; i < arr.length; i++){ // O(arr.length)
sumTotal += arr[i];
}
int sumRight = 0;
int sumLeft=0;
for (int i=1; i < arr.length-1; i++){ // O(arr.length)
sumLeft += arr[i-1];
sumRight = sumTotal - arr[i] - sumLeft;
if (sumRight == sumLeft){
System.out.println("\nFound = "+arr[i]);
break;
}
}
}
public static void main(String[] args) {
int[] numbers = {1,2,2,9,3,2};
System.out.println("Array numbers:");
for (int i=0; i < numbers.length; i++){
System.out.print(numbers[i] + " ");
}
System.out.println("\n");
checkIfEqualOption1(numbers);
}
}
This outputs:这输出:
Array numbers:
1 2 2 9 3 2
Found = 9
I came up with this solution which calculates both sums by increments from left and right positions ( posFromLeft
and posFromRight
in the code below), until the positions have "crossed" each other ( posFromRight > posFromLeft
is not being satisfied anymore):我想出了这个解决方案,它通过从左右位置(下面代码中的posFromLeft
和posFromRight
)的增量来计算两个总和,直到位置相互“交叉”( posFromRight > posFromLeft
不再被满足):
public class Program {
public static void checkIfEqualOption1(int[] arr){
int sumRight = 0;
int sumLeft=0;
int arrayLength=arr.length;
for (int posFromLeft=0; posFromLeft < arrayLength; posFromLeft++){
int posFromRight=arrayLength-posFromLeft-1;
if (posFromRight > posFromLeft){
sumRight+=arr[posFromRight];
sumLeft+=arr[posFromLeft];
}
}
System.out.println("right sum: "+sumRight);
System.out.println("left sum: "+sumLeft);
}
public static void main(String[] args) {
int[] numbers = {1,2,2,9,3};
System.out.println("Array numbers:");
for (int i=0; i < numbers.length; i++){
System.out.print(numbers[i] + " ");
}
checkIfEqualOption1(numbers);
}
}
I have written below code to check the equality of sum of the LHS and RHS array items.我写了下面的代码来检查 LHS 和 RHS 数组项的总和的相等性。 getMidIndex() will return the array index where it found the equality.... getMidIndex() 将返回找到相等的数组索引....
public class Concepts {
public static int getMidIndex(int[] elements) throws Exception {
int endIndex = elements.length - 1;
int startIndex = 0, sumL = 0, sumR = 0;
while (true) {
if (sumL > sumR)
sumR += elements[endIndex--];
else
sumL += elements[startIndex++];
System.out.println("StartIndex: " + startIndex + " Endindex: " + endIndex + " SumLeft: " + sumL
+ " SumRight: " + sumR);
if (sumL == sumR)
break;
if (startIndex > endIndex) {
System.out.println("Invalid Array");
break;
}
}
return endIndex;
}
public static void main(String[] args) throws Exception {
int[] array = { 1, 2, 2, 9, 3, 2 };
int midVal = getMidIndex(array);
System.out.println("Mid index: " + midVal + " Value: " + array[midVal]);
}
}
void balanceArray(int[] arr){
int[] leftArray;
int[] rightArray;
for(int i=0; i<arr.length; i++){
leftArray=Arrays.copyOfRange(arr,0, i+1);
rightArray = Arrays.copyOfRange(arr,i+1, arr.length);
int sumofLeft= sumOfArray(leftArray);
int sumofRight = sumOfArray(rightArray);
if(sumofLeft==sumofRight && sumofLeft!=0){
int L=leftArray.length;
int R=rightArray.length;
return;
}
}
sumOfArray(...) method is as follow. sumOfArray(...) 方法如下。
private int sumOfArray(int[] arr){
int sum=0;
for(int no:arr){
sum+=no;
}
return sum;
}
public void printMiddleIndex(int[] arr) {
int endidx = arr.length-1; // End index
int startidx = 0; // Start index
int ssum =arr[0]; // sum from left end 'start sum'
int esum =arr[endidx]; // sum from right end 'end sum'
while(true) {
System.out.println("Ssum : "+ssum+" Esum : "+esum+" Sindex : "+startidx+" Eindex : "+endidx);
if(ssum>esum)
esum += arr[--endidx];
else if(ssum<esum)
ssum += arr[++startidx];
else if(ssum==esum) {
if(startidx == endidx-1) {
System.out.println("MiddleIndex : "+endidx);
break;
}
ssum += arr[++startidx];
}
else if(startidx > endidx-1) {
System.out.println("Array is not good");
}
}
}
Here's a solution in Python.这是 Python 中的解决方案。 I have used list slicing.我使用过列表切片。 This is having least space complexity running in O(n).这是在 O(n) 中运行的最小空间复杂度。 Here "l" is the input array.这里的“l”是输入数组。
for i in range(len(l)-1):
if sum(l[0:i+1])==sum(l[i+2:]):
print(l[i+1])
Implemented in Javascript but same logic applies.在 Javascript 中实现,但适用相同的逻辑。 This is O(n) solution:这是 O(n) 解决方案:
//returns the index or -1 if not equal sides
function findIndexIfArrayHasEqualSides(arr) {
const sum = arr.reduce((acc, num) => acc += num);
let sumLeft = 0;
let sumRight = 0;
for (let i = 0; i < arr.length; i++) {
const currentVal = arr[i];
sumRight = sum - sumLeft - currentVal;
if (sumLeft === sumRight) {
return i;
}
sumLeft += currentVal;
}
return -1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.