如果有一个分割数组的位置使得一侧的数字总和等于另一侧数字的总和,则给定一个数字数组返回true。 < / p>
Here's as far as I got. Please help:
function splitSum(arr) {
if(arr.length % 2 === 0) {
if ()
}
}
答案 0 :(得分:1)
这可以通过一种非常简单的方式解决:
只需迭代所有可能的位置来分割数组,从一个空的左数组开始,右数组等于输入数组,并计算两个数据块的总和。现在只需将数组中的第一个元素从右侧移动到左侧块。总和以一种非常简单的方式改变:假设我们从右块中删除n
,只需从右块中减去n
并将其添加为左块的总和。
int equilibrium(int[] i)
int splitBefore = 0;
int left = 0;
int right = sumof(i);
for(; splitBefore < length(i) ; splitBefore++)
if(left == right)
return true;
left += i[splitBefore];
right -= i[splitBefore];
return left == right;
答案 1 :(得分:0)
public boolean canBalance(int[] nums) {
int left = 0;
int right=0;
for(int k=0;k<nums.length; k++) {
right+=nums[k];
}
for(int i=0; i<nums.length-1; i++) {
if(left!=right) {
left+=nums[i];
right-=nums[i];
}
}
return left==right;
}
答案 2 :(得分:0)
这里有评论,希望它能解释一切:)
public boolean canBalance(int[] nums) {
int p1 = 0; // a pointer to start of array
int p2 = nums.length-1; // a pointer to end of array
int sum1=0;// sum1 for left side elements sum taken care by p1
int sum2=0;// sum2 for right side elements sum taken care by p2
for(int i=0;i<nums.length;i++){
//run upto the length of array
sum1+=nums[p1]; // summing left side elements
sum2+=nums[p2];//adding right side elements
if(sum1==sum2 && Math.abs(p1-p2) == 1){
//if two sums become equal and the pointers differ by only one position
//then we got the answer
return true;
}
if(sum1 == sum2){
//two sums are equal means elements are equal on both sides
//hence move both pointers
p1++;
p2--;
}
else if(sum1 > sum2){
// sum1 is greater then need to make sum2 bigger hence move p2
p2--;
sum1-= nums[p1];//removing repeated addition when p2 is changed
}
else{
// sum2 is greater then need to make sum1 bigger hence move p1
p1++;
sum2-=nums[p2];//removing repeated addition when p1 is changed
}
}
return false;
}
答案 3 :(得分:0)
public boolean canBalance(int[] nums) {
int leftSum = 0;
int rightSum = 0;
for (int i = 0; i < nums.length; i++){
leftSum += nums[i];
for (int j = i+1; j < nums.length; j++){
rightSum += nums[j];
}
if (leftSum == rightSum)
return true;
rightSum = 0;
}
return false;
}
答案 4 :(得分:0)
我以不同的方式解决了这个问题。如果我们想将数组拆分为相等的数组,则数组必须能被 2 整除。当您从左侧开始添加列表时,您将到达一个点,左侧将等于总数的一半。
public boolean canBalance(int[] nums) {
int total = 0, half = 0;
for(int i = 0; i < nums.length; i++)
{
total = nums[i] + total;
}
if(total % 2 == 1)
{
return false;
}
for(int i = 0; i < nums.length; i++)
{
half = nums[i] + half;
if(half == total / 2)
{
return true;
}
}
return false;
}
答案 5 :(得分:0)
Python 中的解决方案:
a = [2,1,1,2,1]
for i in range(len(a)):
a1 = a[:i+1]
a2 = a[i+1:]
if sum(a1) == sum(a2):
print(a1)
print(a2)