我已经解决了编纂的第一项任务(TapeEquilibrium)。
我已经获得了50%的分数(100%的正确性,0%的表现)。
你能给我一些提示我如何提高表现。
我的结果和问题说明的链接是here。
代码如下:
import java.util.*;
class Solution {
public int solution(int[] A) {
List<Integer> splittedTape = new ArrayList<Integer>();
for (int i = 1; i < A.length; i++){
splittedTape.add(calculateDifference(i, A));
}
Collections.sort(splittedTape);
return splittedTape.get(0);
}
private int calculateDifference(int position, int[] array){
int sumA = 0;
int sumB = 0;
for (int i = 0; i < array.length; i++){
if (i < position){
sumA += array[i];
} else {
sumB += array[i];
}
}
return Math.abs(sumA - sumB);
}
}
提前致谢。
答案 0 :(得分:3)
我还没有完全测试过角落的情况,所以这可能不会产生预期的结果,但这是一个O(N)解决方案,用于实现问题的要求。
class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
int totalSum = 0;
int firstSum = A[0];
for(int i=1;i<A.length;i++)
totalSum += A[i];
int min = Math.abs(firstSum-totalSum);
for(int i=1;i<A.length-1;i++) {
firstSum+=A[i];
totalSum-=A[i];
if(Math.abs(firstSum-totalSum)<min)
min = Math.abs(firstSum-totalSum);
}
return min;
}
}
答案 1 :(得分:0)
下面的Java解决方案使100%具有O(n)复杂性。
public static int solution(int[] A) {
int accumulator = 0;
int originalArrayLength = A.length;
int[] accumulatedArray = new int[originalArrayLength];
for (int i = 0; i < originalArrayLength; i++) {
accumulator += A[i];
accumulatedArray[i] = accumulator;
}
int max = accumulatedArray[originalArrayLength - 1];
int minAbsoluteDiff = Integer.MAX_VALUE;
for (int i = 0; i < accumulatedArray.length - 1; i++) {
int firstSum = accumulatedArray[i];
int secondSum = max - firstSum;
int absoluteDiff = Math.abs(firstSum - secondSum);
if (absoluteDiff < minAbsoluteDiff) {
minAbsoluteDiff = absoluteDiff;
}
}
答案 2 :(得分:0)
代码更容易理解:
class Solution {
public int solution(int[] numbersOnATape) {
int minimalDifference = Integer.MAX_VALUE;
int sumOfFirstPart = 0;
int sumOfSecondPart = sumOfValuesInsideOfTheTap(numbersOnATape);
for (int count = 0; count < numbersOnATape.length - 1; count++) {
int currentNumber = numbersOnATape[count];
int nextNumber = numbersOnATape[count + 1];
sumOfFirstPart += currentNumber;
int difference = Math.abs(sumOfFirstPart - sumOfSecondPart);
if (minimalDifference > difference) {
minimalDifference = difference;
}
sumOfSecondPart -= nextNumber;
}
return minimalDifference;
}
private int sumOfValuesInsideOfTheTap(int[] numbersOnATape) {
int sumOfValuesInsideOfTheTap = 0;
for (int count = 1; count < numbersOnATape.length; count++) {
sumOfValuesInsideOfTheTap += numbersOnATape[count];
}
return sumOfValuesInsideOfTheTap;
}
}
得分100%
答案 3 :(得分:0)
以下Swift解决方案给出了84%的O(n)复杂度
#include<iostream>
using namespace std;
void Hi(int a)
{
cout << "Hi" << a << endl;
}
int main()
{
auto Print = Hi;
Print(5);
}