Codility通过汽车

时间:2014-05-21 05:49:46

标签: java

给出了由N个整数组成的非空零索引数组A.阵列A的连续元素代表道路上的连续车辆。

数组A仅包含0和/或1:

    0 represents a car traveling east,
    1 represents a car traveling west.

目标是计算过往车辆的数量。我们说一对汽车(P,Q),其中0≤P<1。 Q&lt;当P向东行驶而Q向西行驶时,N正在经过。

例如,考虑数组A:

  A[0] = 0
  A[1] = 1
  A[2] = 0
  A[3] = 1
  A[4] = 1

我们有五对过往车辆:(0,1),(0,3),(0,4),(2,3),(2,4)。

写一个函数:

class Solution { public int solution(int[] A); } 

给定N个整数的非空零索引数组A,返回过往车辆的数量。

如果过往车辆的数量超过1,000,000,000,该功能应返回-1。

例如,给定:

  A[0] = 0
  A[1] = 1
  A[2] = 0
  A[3] = 1
  A[4] = 1

该函数应返回5,如上所述。

假设:

    N is an integer within the range [1..100,000];
    each element of array A is an integer that can have one of the following values: 0, 1.

复杂度:

    expected worst-case time complexity is O(N);
    expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).

可以修改输入数组的元素。

我不明白为什么有五辆过往车,而不是6.为什么不(2,1)算作过往车?有人可以就如何解决这个问题提供一些解释吗?

53 个答案:

答案 0 :(得分:10)

这是我在C#中获得100%的代码

class Solution
{
    public int solution(int[] A)
    {
        int count = 0;
        int multiply = 0;
        foreach (int car in A)
        {
            if (car == 0)
            {
                multiply = multiply + 1;
            }
            if (multiply > 0)
            {
                if (car == 1)
                {
                    count = count + multiply;
                    if (count > 1000000000)
                    {
                        return -1;
                    }
                }
            }
        }
        return count;
    }
}

答案 1 :(得分:8)

时间复杂度 - O(n) 空间复杂性 - O(1) 我提出的逻辑是这样的。

  • 有2个变量。计数和增量值。将两者初始化为零。
  • 遍历阵列。每次找到0时,递增IncrementVal。
  • 每次找到1时,都会通过将incrementVal添加到count来修改计数。
  • 完成数组遍历后,返回计数。

注意::下面提供的示例代码假定为静态数组和预定义的数组大小。你可以使用矢量使它动态化。

#include <iostream>
using namespace std;

int getPass(int* A, int N)
{
    unsigned long count = 0;
    int incrementVal = 0;
    for(int i = 0; i < N; i++)
    {
        if(A[i]==0)
        {
            incrementVal++;
        }
        else if (A[i]==1)
        {
            count = count + incrementVal;
        }
        if(count > 1000000000) return -1;
    }
    return count;
}

int main()
{
   int A[]={0,1,0,1,1};
   int size = 5;
   int numPasses = getPass(A,size);
   cout << "Number of Passes: " << numPasses << endl;
}

答案 2 :(得分:8)

您需要计算汽车通行次数。汽车位于道路上,如输入所示,并开始驶入任何一个方向。当汽车行驶时,我们可以很容易地看到汽车将在相反的方向上行驶,但前提是它们位于汽车前方。基本上可以表述为:

  1. 想象一下数组0..N

  2. 取元素X(从0到第N个元素迭代)

  3. 如果元素X的值为0,则计算右侧有多少1个元素

  4. 如果元素X的值为1,则计算它左边有多少0个元素

  5. 重复下一个X

  6. 总结并除以2(因为它需要2辆汽车相互通过),这就是答案。

  7. 如果0 1 0 1 1我们有3 + 1 + 2 + 2 + 2 = 10.除以2 = 5次传递。

    我们不计算第2-1对,因为第二辆车正在向东方行驶,并且从未将第一辆车驶离西方。

答案 3 :(得分:6)

这是Java中的简单示例。我认为它应该100%传递

public int solution(int[] A) {
        int countOfZeros = 0, count = 0;

        for (int i = 0; i < A.length; i++){
            if (A[i] == 0) countOfZeros++;                    
            if (A[i] == 1) count += countOfZeros;    
            if (count > 1000000000) return -1;
        }
        return count;
}

答案 4 :(得分:4)

100%JavaScript。背后的逻辑是每辆西方汽车(1)与所有前面的东方汽车(0)创建一对。因此,每次我们得到1时,我们都会添加前面的所有0。

function solution(A) {
    var zeroesCount = 0; //keeps track of zeroes
    var pairs = 0; //aka the result

    for (var i=0; i<A.length; i++) {
        A[i]===0 ? zeroesCount++ : pairs += zeroesCount; //count 0s or add to answer when we encounter 1s

        if (pairs > 1000000000 ) { //required by the question
            return -1;   
        }
    }

    return pairs;
}

答案 5 :(得分:2)

这是我的JavaScript解决方案,得分为100%,时间复杂度为O(n)。

function solution(A) {
  let pairsCount = 0;
  let eastBound = 0;
  let incCounter = 0;
  for (let i = 0; i < A.length; i++) {
    // If current car is east bound, increment the counter by 1
    // next time onwards, when westbound car comes, par count would be increased by increased counter
    if (eastBound === A[i]) {
      incCounter++;
    } else {
      pairsCount += incCounter;
    }
  }
  return pairsCount <= 1000000000 ? pairsCount : -1;
}

答案 6 :(得分:2)

这里的大多数答案只是提供了解决任务的算法,而没有回答作者的原始问题。 “ 为什么只有5对车而不是6 ?”这是因为汽车(2,1)从不相互通过。

这里是问题的快速可视化。 enter image description here

答案 7 :(得分:2)

我知道这个答案我已经很晚了。 虽然我给出的解决方案是100%正确性和表现能力。

Notice: Undefined index: symbol in ...

我所遵循的方法如下:

将数组从最后一个元素迭代到第一个元素(反向)
增加计数直到你得到1
当你找到0时,将你的1的计数加到countPair 在数组countPair的迭代结束时你的答案。

答案 8 :(得分:2)

这是我在C中的解决方案,它得分为100%并且很容易理解。诀窍是向后穿过数组

int solution(int A[], int N) 
{

int goingWest = 0; 
int passes = 0;

for(int i = N-1; i >= 0; i--)
{
    if(A[i] == 1)
    {
        goingWest++;   
    }
    else
    {
        passes += goingWest;   

        if(passes > 1000000000)
        return -1;
    }
}
return passes;

}

答案 9 :(得分:2)

回答问题中的原始问题:

0 ≤ P < Q < N

对于所有对(P,Q),P必须在Q之前出现.2不在1之前。

你也可以从最后开始工作,积累1来匹配下一个0:

public int solution(int[] A) {
    int ones =0, count=0;
     for (int j = A.length-1; j >=0; j--) {
         if (A[j] ==1) {
             ones++;
         } else if (A[j] ==0) {
             count+=ones;
         }             
         if ( count > 1_000_000_000) {
           return     -1;
         }
     }
     return count;
 }

答案 10 :(得分:1)

100/100 in C。

 I/Choreographer(1378): Skipped 55 frames!  The application may be doing too much work on its main thread. 

答案 11 :(得分:1)

100% 的编码和 javascript

function solution(A) {
// let consider car going east be the one we choose. when we go east and find any cars going west increment the count and add the increment to the pairs 
const len = A.length;
let count = 0; 
let pairs = 0; 
for( let i = 0; i < len; i++) {
    if (A[i] === 0) count++;
    if (A[i] === 1) pairs = pairs + count;
    if (pairs > 1000000000) {
        pairs = -1;
        break;
    }
}
return pairs;

}

答案 12 :(得分:1)

Codality link 在Java中。

    // you can also use imports, for example:
// import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
    public int solution(int[] A) {
        // write your code in Java SE 8

        int sum = 0;
        int occurence = 0;

        for ( int i =0 ; i < A.length; i ++ )
        {

            if ( A[i] == 0 )
                occurence++;
            else
            {
                sum+=occurence;
                if ( sum > 1000000000 )
                    return -1;
            }
        }

        return sum;
    }
}

答案 13 :(得分:1)

在Objective-c中100% https://codility.com/demo/results/demoKEEN2X-N8V/

int passingCars(NSMutableArray* a)
{
    if (a.count <= 1)
    {
        return 0;
    }
    int passingCars = 0;
    int goingEast = 0;

    for (int i = 0; i < a.count; i ++)
    {
        if ([a[i] intValue] == 0)
        {
            goingEast++;
        }
        else
        {
            passingCars += goingEast;
            if (passingCars > 1000000000)
            {
                return -1;
            }
        }
    }
    return passingCars;
}

答案 14 :(得分:0)

这是另一种使用前缀和的方法,其Codility得分为100%。

public int solution(int[] A) {
    int[] onesAfterIndex = new int[A.length];
    int oneCount = 0;
    for (int i = A.length - 1; i >= 1; i--) {
        if (A[i] == 1) {
            oneCount++;
        }

        onesAfterIndex[i - 1] = oneCount;
    }

    int pairs = 0;
    for (int i = 0; i < A.length; i++) {
        if (A[i] == 1) {
            continue;
        }

        pairs += onesAfterIndex[i];
        if (pairs > 1000000000) {
            pairs = -1;
            break;
        }
    }

    return pairs;
}

答案 15 :(得分:0)

我在Swift中使用SaffixSums的答案

public func SuffixCount(_ A : inout [Int]) -> [Int] {

    var P = [Int](repeating: 0, count: A.count+1)

    P[A.count] = 0

    for i in stride(from: A.count-1, to: 0, by: -1) {
        P[i] = P[i+1] + A[i]
    }

    return P
}

A = [0, 1, 0, 1, 1]
print("SufficeCount: ", SuffixCount(&A))

public func PassingCars(_ A : inout [Int]) -> Int {

    let P = SuffixCount(&A)

    var result = 0

    for i in  0..<A.count {

        if A[i] == 0 {
            result += P[i+1]
        }
    }

    return result
}

print("PassingCars: ", PassingCars(&A))

答案 16 :(得分:0)

使用前缀和解决Java中的O(N)时间复杂度

class Solution 
{
    public int solution(int[] A) {

        int N = A.length;
        int[] P = new int[N+1];
        int sum = 0;

        for(int i=1; i < N+1; i++){
            P[i] = P[i-1] + A[i-1];
        }

        for(int i=0; i < N; i++){
            if(A[i]==0)
            {
              sum += P[N] - P[i];
            }

        }

        if( sum > 1000000000 || sum < 0 )
        {
          return -1;
        }

        return sum;


    }
}

答案 17 :(得分:0)

我们正在寻找一对汽车(P,Q),其中0≤P

您的案件(2,1)未通过要求。

我的方法很简单。对于每个1值,我们必须计算先前的零。

我的代码在JAVA中获得100%的时间复杂度为O(n):

class Solution {
    public int solution(int[] A) {
        int count = 0;
        int zeroCount = 0;
        for (int i = 0; i < A.length; i++) {
            if (A[i] == 0) {
                zeroCount++;
            } else if (A[i] == 1) {
                count += zeroCount;
            }
        }
        return count >= 0 && count <= 1000_000_000 ? count : -1;
    }
}

答案 18 :(得分:0)

这项工作对我来说100%合格完全正确

`

    import java.util.Arrays;
    public class MissingInteger {
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            MissingInteger s = new MissingInteger();
            int[] A = {1, 3, 6, 5, 2, 7 };
            s.solution(A);
        }
         public int solution( int[] A) {
             Arrays.parallelSort(A);
             int minNumber = 1;
             for(int data : A)
             {
                 if(data == minNumber)
                 {
                     minNumber++;
                 }
             }
             System.out.println(minNumber);
             return minNumber;
         }
    }
`

答案 19 :(得分:0)

Scala result

  • 100%得分

  • 时间复杂度:O(N)

  def solution(a: Array[Int]): Int = {
    // write your code in Scala 2.12

    case class Survey(east: Int, pairCount: Int)

    a.foldLeft(Survey(0,0)) {
      (survey, passingCar) =>
        if (passingCar == 0) survey.copy( east = survey.east + 1)
        else {
          if( survey.pairCount > 1000000000) return -1
          survey.copy( pairCount = survey.pairCount + survey.east)
        }
    }.pairCount

  }

答案 20 :(得分:0)

function solution (A) {
  let count0 = 0;
  let total = 0;

  A.forEach((elem) => {
    if (elem === 0) count0++;
    if (elem === 1) {
      total = count0 * 1 + total;
    }
  })

  return total > 1000000000
    ? -1
    : total;
}

答案 21 :(得分:0)

Python解决方案

贪婪等级

  • 任务得分100%
  • 正确性100%
  • 性能100%

代码

def solution(array):
    zero_count = 0
    combinations = 0
    for item in array:
        if item == 0:
            zero_count += 1
        else:
            combinations += zero_count

        if combinations > 1000000000:
            return -1

    return combinations

答案 22 :(得分:0)

这个还不错。

看看所有零位赛车。

跟随零位赛车的每辆车都是可以通过的赛车。

因此,在通过所有零位置赛车时,必须将每个1位置赛车加在一起。

Python解决方案,100%。

def solution(A):
multi = 0
count = 0
for i in A:
    if i == 0:
        multi += 1
    count += multi*i
if count > (10**9):
    return -1
else:
    return count

答案 23 :(得分:0)

使用PHP传递汽车解决方案(100%使用Codility)

function solution($A) {
$count = 0;
$helper = 0;
for($i=0;$i<count($A);$i++){
    if($A[$i]==0){ 
        $helper++;                
    }
    else if($A[$i]==1){
        $count = $count + $helper;
    }
    if($count > 1000000000) return -1;
}
return $count;
}

答案 24 :(得分:0)

我尽力使用前缀和来理解过往的汽车,并指出一些注释希望对某些人有帮助...

  

说明   “”       https://app.codility.com/demo/results/trainingRNUS6P-6QQ/       100%       理念-       之前-我们只能使用两个循环,第二个循环中的每个零计数数1都为大o n2

But lets use prefix sum to do it in linear time-
As per question explanation we have to find the total pairs of ones with zeros towards east direction ie. right to left
In order to find that we can use prefix sum ie.
prefix_sum = for any index it represents the total number of cars, which can not pass to any of its right side cars
#               reason is only east moving car can pass to other cars as per problem statement

So what we do is  - First find the # first_car_crosses_max - this is the first car which crosses all the cars to right/ moving to east of it
Now for each car(zero/0) moving car we have to do first_car_crosses_max - prefix_sum[index] why we do see below-
Why? The prefix sum for this index is the number of cars which are to the left side and for sure they will not pass current index car
so we subtract all of these cars and we found the only cars which are moving to east direction passing all others cars. At this point we are
100 % sure that all cars(1) must be passed by this car by definition of first_car_crosses_max

See below- assume moving cars only in east direction, since given in question 0 ≤ P < Q < N so just assume that west car moving is still
west<<<<<------>>>>>>>east
0->>> travels east(passes 3 cars) 1 0->>> travels east(passes 2 cars) 1 1
0 1 0 1 1
for first zero do prefix sum if current is 1 add with previous value
0 1 1 2 3
"""
  

代码

def solution(A):
print("Input      " + str(A))
ar_length = len(A)
# prefix_sum - for any index it represents the total number of cars which can not pass to any of its right side cars
#               reason is only east moving car can pass to other cars as per problem statement
prefix_sum = [0] * (ar_length + 1)
for i in range(1, ar_length + 1):
    prefix_sum[i] = prefix_sum[i - 1] + A[i - 1]

num_passing_cars = 0
print("prefix_sum " + str(prefix_sum))
# first_car_crosses_max - this is the first car which crosses all the cars to right of it
first_car_crosses_max = prefix_sum[ar_length]
print("first_car_crosses_max " + str(first_car_crosses_max))
for index, car in enumerate(A):
    # 0 represents a car traveling east and we have to find the passing cars for zero so that we can find the total number of pairs/crossings
    if car == 0:
        print("")
        print("Can not pass cars " + str(prefix_sum[index]))
        print("Can pass car at current index " + str(first_car_crosses_max - prefix_sum[index]))
        # just subtract from max so we get the total cars passing at this point
        num_passing_cars += (first_car_crosses_max - prefix_sum[index])
        print("Index     " + str(index))
        print("Total num_passing_cars     " + str(num_passing_cars))
        # 10 ** 9 = 1000,000,000, exit for boundary condition as given in question
        if num_passing_cars > 10 ** 9:
            return -1
return num_passing_cars
  

运行

 result = solution([0, 1, 0, 1, 1])
 print("")
 print("Solution " + str(result))

"""
Input      [0, 1, 0, 1, 1]
prefix_sum [0, 0, 1, 1, 2, 3]
first_car_crosses_max 3

Can not pass cars 0
Can pass car at current index 3
Index     0
Total num_passing_cars     3

Can not pass cars 1
Can pass car at current index 2
Index     2
Total num_passing_cars     5

Solution 5
"""

答案 25 :(得分:0)

我的JavaScript解决方案测试了100%

function solution(A) {
    let pairs = 0;
    let totalNumberOfZeros = 0;
    let totalPairs = 0;
    for(let i=0; i<A.length; i++) {
        if(A[i] === 0) {
            totalNumberOfZeros++;
            pairs = 0;
        }
        if(A[i] === 1) {
            pairs = 1;
            totalPairs += (totalNumberOfZeros*pairs);
        }
    }
    if(totalPairs > 1000000000) {
        totalPairs = -1;
    }
    return totalPairs;
}

答案 26 :(得分:0)

我们只需要遍历零点,以便找到总交叉点的数量。

无需为Ones运行额外的代码,因为我们检查的每个Zero的交叉数等于我们检查所有Ones的特定零点时的交叉数。

public class passingCars {


public static void main(String[] args) {
    int k;
    int cnt = 0;
     // Test array
    int[] A = { 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1 };

    for (int i = 0; i < A.length; i++) {

        if (A[i] == 0) {
            k = i + 1;
            while (k < A.length) {
                if (A[k] == 1) {
                    cnt++;
                }
                k++;
            }

        }

    }

    System.out.println(cnt);

}

}

结果:1​​7

答案 27 :(得分:0)

使用流无法获得100%,只有90%。我确信使用流可以有更好的性能。如果有人可以帮忙,谢谢!!

LinkedList<Integer> results = IntStream.range(0, A.length)
                .collect(LinkedList::new, (list, i) -> {
                    if (A[i] == 0) {
                        if (list.size() > 0) {
                            list.add(list.getLast());
                        } else {
                            list.add(0);
                        }
                    } else if (A[i] == 1) {
                        if (!list.isEmpty()) {
                            int lastIndex = list.size() - 1;
                            int current = list.getLast();
                            current += lastIndex + 1;
                            list.set(lastIndex, current);
                        }
                    }
                }, LinkedList::addAll);
        return results.isEmpty() ? 0 
                : results.get(results.size() - 1) > 1000000000 || results.get(results.size() - 1) < 0 ? -1 
                : results.get(results.size() - 1);

答案 28 :(得分:0)

针对Codility PassingCars问题的简单Java解决方案,%100正确的%100性能解决方案,从结束计数1s到0,再将#of 1s加到0。

public int solution(int[] A) {
        int countOne = 0, result = 0, n = A.length;
        //bactracking and adding # of 1s to result when met with 0
        while (n >= 1) {
            if (A[n - 1] == 1)
                countOne++;
            else
                result += countOne;
            n--;

            if (result > 1000000000)
                return -1;
        }
        return result;

    }

答案 29 :(得分:0)

这是100分的解决方案。

  using System;

    class Program
    {
        static void Main(string[] args)
        {
            int[] A = { 0, 1, 0, 1, 1 };
            int N = A.Length;
            int[] ps = new int[N + 1];
           long calc = 0;

//caluclate prefix sums
            for (int i = 1; i <= N; i++)
            {
                ps[i] = A[i - 1] + ps[i - 1];
            }

            for (int i = 0; i < N; i++)
            {
//for each zero count no of 1s to the right.
                if (A[i] == 0)
                {
                    calc += ps[N] - ps[i + 1];
                }
//for each 1 calculate the no of 1s to the left.
                else
                {
                        calc += i+1 - ps[i+1];
                }
            }
            calc = calc / 2;
            if (calc > 1000000000)
                calc = -1;
        }
    }

答案 30 :(得分:0)

def prefix_sums(A):     n = len(A)     p = [0] *(n + 1)     for x in xrange(1,n + 1):         p [k] = p [k - 1] + A [k - 1]     返回p

我相信时间复杂度是O(N ^ 2)

def解决方案(A):     lenA = len(A)     x = 0     numPassingCars = 0     我在A:         x + = 1         对于A [x:]中的j:             如果i == 0且j == 1:                 numPassingCars + = 1                 如果numPassingCars&gt; 10亿:                     返回-1     return numPassingCars

我相信时间复杂度是O(N ^ 2)

def solution2(A):

lenA = len(A)
numPassingCars = 0
counter = 0

for x in A:
    counter += 1
    if x == 0:
        numPassingCars += sum(A[counter:])
        if numPassingCars > 1000000000:
            return -1

return numPassingCars

我相信时间复杂度是O(N)

def solution3(A):

lenA = len(A)
numPassingCars = 0
counter = 0
ps = prefix_sums(A)

for x in A:

    if x == 0:
        numPassingCars += (ps[lenA] - ps[counter])
        if numPassingCars > 1000000000:
            return -1
    counter += 1

return numPassingCars

B = [0,1,0,1,1]

打印解决方案(B) 打印解决方案2(B) print solution3(B)

输出:

5
5
5

答案 31 :(得分:0)

static public int solution(int[] A) {
         int count=0;
         for(int i=0;i<=A.length-1;i++) {
             if(A[i]==0) {
                 for(int j=i; j<A.length-1;j++) {
                     if(A[i]!=A[j+1]) {
                         count+=1;
                     }
                 }
             }
         }
         return count==1000000000?-1:count;
        }

答案 32 :(得分:0)

VB.NET中的代码,具有100个准确性和性能

.

See the results here

答案 33 :(得分:0)

My Solution:C#

上的100 \ 100
public int solution(int[] A) {
    // write your code in C# 6.0 with .NET 4.5 (Mono)

        int west = 0; //  1
        int east = 0; //  0
        int pairsCounter = 0;
        if (A.Length < 0 || A.Length > 100000)
            return 0;

        if (A.Length == 2 && A[0] == 0 && A[1] == 1)
            return 1;
        // finds all west moving cars
        for (int i = 0; i < A.Length; i++)
        {
            if (A[i] == 1)
                west++;
        }

        east = A.Length - west;

        if (east == 0 || west == 0)
            return 0;

        //if (east >= west) // a possible error in test case on codility. It let it be the situation when P >= Q situation, while P < Q < N
        //    return 0;


        for (int i = 0; (i < A.Length && west > 0); i++)
        {
            if (A[i] == 0 && west > 0)
            {   // calculates the combinations
                pairsCounter = pairsCounter + west;
            }
            else
            {
                west--;
            }

            if (pairsCounter > 1000000000)
                return -1;

        }


        return pairsCounter;

}

答案 34 :(得分:0)

对于每个0,存在一个有效的对,后面会出现每1个。 Java解决方案:

class Solution {
public int solution(int[] A) {
    int countZeros=0;
    int sumOfValidPairs=0;
    int i=0;

    while(i<A.length){
        if(A[i] == 0){
            countZeros++;
        }
        else{
            sumOfValidPairs += countZeros;
        }
        i++;
    }
    //handle overflow with ">=0"
    if(sumOfValidPairs <= 1000000000 && sumOfValidPairs >= 0){
    return sumOfValidPairs;
    }
    return -1;
  }

}

答案 35 :(得分:0)

如果它在概念上有所帮助,可以考虑所有停放的汽车的位置,发动机关闭并且按照阵列的顺序面向东或西。然后他们都开始引擎然后开始驾驶......因此,2号车和1号车从未相互通过。

答案 36 :(得分:0)

Java中的解决方案,100%的代码:

public int solution(int[] A) {

    int countZro = 0;
    int countCars = 0;

    for(int i=0; i<A.length;i++)
    {
        if(A[i] == 0)
        {
            countZro++;
        }

        if(countZro > 0 && A[i]==1 )
        {
            countCars += countZro;

        }

         if(countCars>1000000000)
         {
             return -1;
         }
    }

    return countCars;

}

答案 37 :(得分:0)

这是一个包含一些测试用例的Java 100解决方案。

// https://codility.com/demo/results/demoHECS6Y-NF5/ 100

public class PassingCars {
  // [0,0,0,0,0] = 0
  // [0,0,1,1,1,1] = 8
  // [0,0,1,1,1,1,0] = 8
  // [1,0] = 0
  // [0,1,1,1,1,1,1,0] = 6
  // [1,1,1,1,0,1,0] = 1
  // [1,1,1,1,0,1,1,0,1] = 4
    public static final int FAIL = -1;

    public int solution(int[] A) {
        int N = A.length;

        if ( N < 2) { return 0; }

        int onesCount = 0;
        boolean zeroHappenedBefore = false;
        for (int i =0; i < N; ++i ) {
            if(zeroHappenedBefore && A[i] == 1 ) {
                ++onesCount;
            } else if (A[i] == 0) {
                zeroHappenedBefore = true;
            }
        }

        if (onesCount ==0) { return 0; }

        long combinations = 0;
        int conditionReturnFail = 1000000000;
        zeroHappenedBefore = false;

        for (int i=0; i < N; ++i) {
            if (A[i] == 0) {
                combinations += onesCount;
                if(conditionReturnFail < combinations) {
                    return FAIL;
                }
                zeroHappenedBefore = true;
            } else {
                if (zeroHappenedBefore) {
                    --onesCount;
                }
            }
        }

        return (int) combinations;
    }

}

答案 38 :(得分:0)

我在java中的代码,具有O(N)复杂性。更容易理解。只是向后总结所有的。

void calculateOnes(int[] A, int[] sum) {
    int N = A.length;
    sum[N - 1] = A[N - 1];
    for (int i = N - 2; i >= 0; i--) {
        sum[i] = A[i] + sum[i + 1];
    }
}

public int solution(int[] A) {
    int N = A.length;
    int[] sum = new int[N];
    calculateOnes(A, sum);
    int counter = 0;
    for (int i = 0; i < N; i++) {
        if (A[i] == 0) {
            counter += sum[i];
        }
    }
    return counter;
}

答案 39 :(得分:0)

这里你有我的100/100 java代码,我按照Siegfried指出的相同方法(即向后迭代数组)

class Solution {
    public int solution(int[] A) {
        final int MAX_RESULT = 1000000000;
        int result = 0, one_counter=0;
        for(int i=A.length-1; i>=0; i--) {
            if(A[i]==1) {
                one_counter++;
            }
            else {
                if(result>MAX_RESULT) {
                    return -1;
                }
                result+=one_counter;                
            }
        }
        return result;
    }
}

这个解决方案的关键是倒退,计算一个,然后计算每个0和那个点数。

https://codility.com/demo/results/trainingN54WY5-HXT/

答案 40 :(得分:-1)

Java:我用简单的方式做到了100%的正确性和性能

public int solution(int[] A) {
        // write your code in Java SE 8
         int output = 0;
      int noOfZero = 0;
      for (int i = 0; i < A.length; i++) {
         if (A[i] == 0) {
            noOfZero += 1;
            continue;
         }
         if (A[i] == 1 && noOfZero > 0) {
            output += noOfZero * A[i];
         }
      }
      if(output > 1000000000 || output < 0){
         return -1;
      }

      return output;
    }

答案 41 :(得分:-1)

这是我的答案。我得到100%的抄袭能力。

@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
    TextView textView = (TextView) view;
    ((TextView) adapterView.getChildAt(0)).setTextColor(Color.RED);
    ((TextView) adapterView.getChildAt(0)).setTextSize(20);
    Toast.makeText(this, textView.getText()+" Selected", Toast.LENGTH_SHORT).show();
}

答案 42 :(得分:-1)

我使用Swift获得了100%的收益。

public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 4.2.1 (Linux)
var eastCars = 0
var crossings = 0

for numb in A {
    if numb == 0 {
        eastCars += 1
    }else {
        crossings += eastCars
        if crossings > 1000000000 {
            return -1
        }
     }
  }
 return crossings
}

答案 43 :(得分:-1)

JavaScript中的100%

    var i, len = A.length, west = 0, count = 0;
    
    for (i = 0; i < len; i++){
        if (A[i]) west++;            
    }
    
    for (i = 0; i < len; i++){
        if (!A[i]) count += west;
        if (A[i]) west--;
        if (count > 1000000000) return -1;
    }
    
    return count;

答案 44 :(得分:-1)

我对JAVA的解决方案

type IntList = [Int]
type StrList = [String]

data MyIntStr = MyIntStr { intList :: IntList, strList :: StrList }
              deriving Show

empty :: MyIntStr
empty = MyIntStr [] []

putInts :: [Int] -> MyIntStr -> MyIntStr
putInts is (MyIntStr is' ss) = MyIntStr (is'++is) ss

答案 45 :(得分:-1)

C ++灵魂与100%的结果:

int solution(vector<int> &A) {
// write your code in C++11
int zeroCount=0;
int passingCars=0;
for(vector<int>::iterator itr= A.begin();itr!=A.end(); itr++)
  {  if(*itr==0)
        zeroCount++;
    else
        passingCars+=zeroCount;
    if(passingCars>1000000000)
        return -1;
  }
return passingCars;

}

答案 46 :(得分:-1)

int solution(vector<int> &A) {
    // write your code in C++11 (g++ 4.8.2)
    int sum=0;
    vector<int>::iterator pt_last_one = A.end();

    // build the prefix sum
    for (vector<int>::iterator pt = A.begin(); pt!=A.end(); pt++) {
            sum+=*pt;
        if (*pt == 1) {
            *pt=sum;
            pt_last_one=pt;
        }
    }

    if (pt_last_one == A.begin() || pt_last_one == A.end() ) return 0;

    sum=0;
    int last_zero_pt=0;

    // count passing cars
    for (vector<int>::iterator pt = A.begin(); pt!=A.end(); pt++) {
        if (*pt==0 && (pt+1)!=A.end()) {
            sum+=*pt_last_one-last_zero_pt;            
        } else if (*pt!=0)
            last_zero_pt = *pt;

        if (sum >1000000000) return -1;
    }

    return sum;
}

答案 47 :(得分:-1)

Objective-C溶液100%

int solution(NSMutableArray *A) {
// write your code in Objective-C 2.0


int n=0;
int long long t = 0;

for(int i=0;i<A.count;i++)
{
    if([A[i] intValue]==0)
    {
        n=n+1;
    }

    else
    {
        t = t+n*1;
    }    
}

 if(t>1000000000)
 {
    return -1;
 }
 else
 {
    return t;
 }
}

答案 48 :(得分:-1)

我的Java解决方案在正确性和性能方面均获得100分。

public int solution(int[] A) {
    if(A.length<2) {
        return 0;
    }
    long passingPairs = 0;
    long eastBound = 0;
    for (int i = 0; i < A.length; i++) {
        if (A[i] == 0) {
            eastBound++;
        } else  {
            if(eastBound>0) {
                passingPairs += eastBound;
            }
        }

    }

    return passingPairs>1000000000?-1:(int)passingPairs;
}

答案 49 :(得分:-1)

C#:谁更矮? ; - )

public int solution(int[] cars, int N)
{
  var sum = 0;
  for (var i = 0; i < N; i++)
  {
    if (cars[i]==1)
      continue;
    sum += cars.Skip(i).Aggregate((a, b) => a + b);
    if (sum > 1000000000)
      return -1;
  }
  return sum;
}

答案 50 :(得分:-2)

Objective-c功能:

-(int)carPairCount:(NSMutableArray *)A {

    if ( A.count > 0 )
    {
        int N = (int)A.count;
        int P = 0;
        int Q = 1;
        int count = 0;

        while ( P < Q && Q < N ) {

            if ([A[P] intValue] == 0 && [A[Q] intValue] == 1) {
                count++;

                if ( count > 1000000000)
                    return -1;
            }

            Q++;
            if ( Q == N )
            {
                P++;
                Q = P+1;
            }
        }

        return count;
    }

    return 0;
}

答案 51 :(得分:-2)

在C中传递汽车解决方案

int solution(int A[], int N) {
    // write your code in C90
    int i=N-1,j=0,k=0;

    do
    {
        if (A[i]==0)
        {
            j+=k;
            if (j>1000000000)return -1;
        }
        else
            k += 1;

    }while(--i>=0);

    return j;
}

答案 52 :(得分:-2)

C#解决方案:

&#13;
&#13;
 public int solution(int[] A) {
        // write your code in C# 6.0 with .NET 4.5 (Mono)
        int carsEast = 0;
            int carPairs = 0;
            for (int i = 0; i < A.Length; i++)
            {
                carsEast = A[i] == 0 ? carsEast+=1 : carsEast;
                carPairs = A[i] == 1 && carsEast > 0 ? carPairs + carsEast : carPairs;
                if (carPairs > 1000000000)
                {
                    return -1;
                }
            }
            return carPairs;
    }
&#13;
&#13;
&#13;

相关问题