今天剛做完網易的筆試題,對其中一道編程題印象特別深刻:
題目的主要題幹:對數列A進行重排序,使得所有的A[i]*A[i+1]都是4的倍數
我的思路是這樣的:
要找出此數列的規律,其實並不需要每種情況都遍歷判斷一遍,而是要搞清楚能滿足條件時數列必須滿足的形式。兩個數相乘是4的倍數,即要麼至少有一個數能被4整除,要麼兩個數能被2整除。也就是說數列中所有兩個數的組合相乘必須要滿足一種情況。
從而想到需要統計能被4整除的個數,能被2整除的個數和不能被4,2整除的個數。見如下代碼:
#include <bits/stdc++.h>
using namespace std;
int n;
int main() {
int t;
scanf("%d", &t);//需要判斷幾個數列
while(t--) {
scanf("%d", &n);//每個數列的長度
int cnt4 = 0;
int cnt2 = 0;
int cnt1 = 0;
for(int i = 0; i < n; i++) {
int x;
scanf("%d", &x);//數列中具體的數
if(x % 4 == 0) cnt4++;
else if(x % 2 == 0) cnt2++;
else cnt1++;
}
if(cnt2 == 0) {
if(cnt4 >= cnt1 - 1)
printf("Yes\n");
else
printf("No\n");
} else {
if(cnt4 >= cnt1)
printf("Yes\n");
else
printf("No\n");
}
}
return 0;
}