码迷,mamicode.com
首页 > 其他好文 > 详细

Twitter OA prepare: even sum pairs

时间:2015-01-04 06:22:50      阅读:277      评论:0      收藏:0      [点我收藏+]

标签:

Write a function:
class Solution { public int solution(int[] A); }
that, given an array A consisting of N integers, returns the number of pairs (P, Q) such that 0 ≤ P < Q < N and (A[P] + A[Q]) is even. The function should return −1 if the number of such pairs exceeds 1,000,000,000.
For example, given array A such that:
A[0] = 2, A[1] = 1, A[2] = 5, A[3] = −6, A[4] = 9
the function should return 4, because there are four pairs that fulfill the above condition, namely (0,3), (1,2), (1,4), (2,4).
Assume that:
N is an integer within the range [0..1,000,000];
each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].
Complexity:
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).
Elements of input arrays can be modified.

思路:无非就是扫描一遍记录奇数和偶数各自的个数,比如为M和N,然后就是奇数里面选两个、偶数里面选两个、一奇一偶,答案就是M(M-1)/2 + N(N-1)/2 + MN

Twitter OA prepare: even sum pairs

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/4200243.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!