首页 > 试题广场 >

重排数列

[编程题]重排数列
  • 热度指数:64 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 98M,其他语言196M
  • 算法知识视频讲解
小易有一个长度为N的正整数数列A = {A[1], A[2], A[3]..., A[N]}。
牛博士给小易出了一个难题:
对数列A进行重新排列,使数列A满足所有的A[i] * A[i + 1](1 ≤ i ≤ N - 1)都是4的倍数。
小易现在需要判断一个数列是否可以重排之后满足牛博士的要求。

输入描述:
输入的第一行为数列的个数t(1 ≤ t ≤ 10),
接下来每两行描述一个数列A,第一行为数列长度n(1 ≤ n ≤ 10^5)
第二行为n个正整数A[i](1 ≤ A[i] ≤ 10^9)


输出描述:
对于每个数列输出一行表示是否可以满足牛博士要求,如果可以输出Yes,否则输出No。
示例1

输入

2
3
1 10 100
4
1 2 3 4

输出

Yes
No
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int times = sc.nextInt();
            for (int k = 0; k < times; k++) {
                int len = sc.nextInt();
                int[] nums = new int[len];
                int count_4 = 0;
                int count_2 = 0;
                int count_1 = 0;
                for (int i = 0; i < len; i++) {
                    nums[i] = sc.nextInt();
                    if (nums[i] % 4 == 0) {
                        count_4++;
                    } else if (nums[i] % 2 == 0) {
                        count_2++;
                    } else {
                        count_1++;
                    }
                }
                if (count_2 == 0) {
                    System.out.println(count_4 >= count_1 - 1 ? "Yes" : "No");
                } else {
                    System.out.println(count_4 >= count_1 ? "Yes" : "No");
                }

            }
        }
        sc.close();

    }

}
发表于 2018-05-25 22:57:17 回复(0)
def meetRequirement(l):
    fours = 0
    twos = 0
    others = 0
    m = len(l)
    for i,k in enumerate(l):
        if k%4 == 0:
            fours +=1
        elif k%2 == 0:
            twos +=1
        else:
            others +=1
    #即4的倍数的个数大于一半时肯定满足条件
    if fours >= m//2:
        return 'Yes'
    #当4的倍数小于一半时,两个2的倍数必须在一起才满足条件,4的倍数旁边可以加其他数,所以2的倍数的个数大于等于m-2*fours时才满足条件
    elif twos >= m - fours*2:
        return 'Yes'
    else:
        return 'No'
n = int(input())
for _ in range(n):
    m = int(input())
    l = list(map(int,input().split()))
    print(meetRequirement(l))

发表于 2021-03-25 17:14:35 回复(0)
t = int(input())
ns = []
arrays = []
for each in range(t):
    ns.append(int(input()))
    arrays.append([i for i in map(int, input().split())])
count = 0
results = []
while count < t:
    n = ns[count]
    array = arrays[count]
    fours = 0
    twos = 0
    others = 0
    for each in array:
        if each % 4 == 0:
            fours += 1
        elif each % 2 == 0:
            twos += 1
        else:
            others += 1
    if twos == 0:
        if fours >= n // 2:
            results.append('Yes')
        else:
            results.append('No')
    else:
        if fours >= others:
            results.append('Yes')
        else:
            results.append('No')
    count += 1
for each in results:
    print(each)

发表于 2020-10-20 23:13:47 回复(0)