[英]Interview - finding even sum pair in an array
給定一個數組,您將如何返回總和為偶數的對數?
例如:
a[] = { 2 , -6 , 1, 3, 5 }
在此數組中,與偶數和成對的no是(2,-6),(1,3),(1,5),(3,5)
函數應該返回4,因為有4對,如果沒有對則返回-1。
預期時間復雜度-O(N)最壞情況預期空間復雜度-O(N)最壞情況
方法1:蠻力
Start with the first number
Start with second number
assign the sum to a temp variable
check if the temp is even
If it is increment evenPair count
else
increment the second index
這里的時間復雜度為O(N2)
int odd = 0, even = 0;
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 0) {
even++;
} else {
odd++;
}
}
int answer = (odd * (odd - 1) + even * (even - 1)) / 2;
如果使用標准算法,則代碼可以如下所示
#include <iostream>
#include <utility>
#include <numeric>
#include <iterator>
int main()
{
int a[] = { 2 , -6 , 1, 3, 5 };
typedef size_t Odd, Even;
auto p = std::accumulate( std::begin( a ), std::end( a ),
std::pair<Odd, Even>( 0, 0 ),
[]( std::pair<Odd, Even> &acc, int x )
{
return x & 1 ? ++acc.first : ++acc.second, acc;
} );
std::cout << "There are "
<< ( p.first * ( p.first - 1 ) + p.second * ( p.second - 1 ) ) / 2
<< " even sums" << std::endl;
return 0;
}
輸出是
There are 4 even sums
考慮到n! / ( 2! * ( n - 2 )! )
n! / ( 2! * ( n - 2 )! )
等於( n - 1 ) * n / 2
使用標准算法的優點是可以使用序列的任何子范圍。 您也可以使用標准流輸入,因為std::accumulate
使用輸入迭代器。
如果在賦值的描述中寫成如果數組元素之間沒有偶數和,則函數應返回0而不是-1,那會更好。
盡管我建議不要在面試中做任何作業,但在面試中顯示此代碼並不可恥。 面試不是考試。
如果a和b是偶數,則a + b是偶數。
如果它們是奇數,則a + b也是偶數。
如果一個是奇數,一個是偶數,則a + b是奇數。
這意味着我們不需要執行任何加法運算,我們只需要知道每種數字有多少個即可。
找出這一點需要花費線性時間。
如果您有k個數字,則有k-1對包含第一個數字,k-2對包含第二個數字,依此類推。
使用熟悉的求和公式sum(1 .. n) = (n * (n + 1)) / 2
,
讓
ne = number of even numbers
no = number of odd numbers
然后,
number of pairs = (ne-1) * ne / 2 + (no-1) * no / 2
= ((ne-1)*ne + (no-1)*no) / 2
該計算以恆定的時間運行,因此時間復雜度仍然是線性的。
而且我們只需要恆定數量的額外空間,這比需求要好。
可能的后續采訪問題可能值得考慮:
如果發生以下情況,復雜性(在時間和空間上)會發生什么:
{1,1,1,2}
僅具有兩個這樣的對? (1,2)
和(2,1)
是“相同”對嗎? 一種不同的方法是按奇數和偶數計算和的數量,然后求和然后加在一起
int sumO = 0 , sumE = 0 , numO = 0 , numE = 0;
for (int i=0; i < 5; i++)
{
if (a[i] % 2 == 0)
{
sumE += numE;
numE ++;
}
else
{
sumO += numO;
numO ++;
}
}
printf ("Total: %d\n", sumO + sumE);
我從一次采訪中得到了這個問題。 無需將偶數和奇數全部分開。
public static int evenTotalPairs(int[] A) {
int size = A.length;
int evens = 0;
for(int i = 0; i < size; i++ ){
if(A[i] % 2 == 0){
evens++;
}
}
return evens*(evens-1)/2 + (size-evens)*(size-evens-1)/2;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.