「算法」网易笔试算法 重排数组 java

小易有一个长度为N的正整数数列A = {A[1], A[2], A[3]..., A[N]}。牛博士给小易出了一个难题:
     对数列A进行重新排列,使数列A满足所有的A[i] * A[i + 1](1 ≤ i ≤ N - 1)都是4 的倍数。

     小易现在需要判断一个数列是否可以重排之后满足牛博士的要求。

2021-10-27 更新如下:

思路比看到的其他简单点,不知是否仍有没考虑到的case。

        因任意偶数相乘均为4 的倍数;

                即 2n * 2m = 4(n * m)

        且任意4n (4的倍数) 与奇数相乘均为4 的倍数;

                即 4n * m 

        且奇偶(非四倍数)相乘,不为4 的倍数;

                2n * (2n+1) = 4n^2 + 2n

                。。。 反正是永远不为4 倍数,基础不行 写不出过程。

        故可忽略偶数,只判断4n 数量与奇数 数量 1:1 即是符合条件。

                

public class Main {

    private static String f(ArrayList<Integer> arr) {
        int count4 = 0;
        int countOdd = 0;
        for (Integer num : arr) {
            if (num % 4 == 0) {
                count4++;
            } else if ((num & 1) == 1) {
                countOdd++;
            }
        }         
        return count4 >= countOdd ? "Yes" : "No";
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        ArrayList<Integer> list1 = new ArrayList<>();

        for (int i = 0; i < n; i++) {
            int count = 0;
            if (sc.hasNextInt())
                count = sc.nextInt();
            for (int j = 0; j < count; j++) {
                list1.add(sc.nextInt());
            }
            System.out.println(f(list1));
        }
    }
}

=============== 错误的old code 分割线 ===============

import java.util.ArrayList;
import java.util.Scanner;

/**
 * 100 1 10
 * A[i] * A[i+1] % 4 == 0
 * 
 * @author Asus
 *
 */
public class Main {

	private static String f(ArrayList<Integer> arr){
		int count = 0 ;
		for (Integer object : arr) {
			if ( object % 4 == 0 ) {
				count++;
			}
		}
		if ( count >= arr.size()/2) {
			return "Yes";
		}
		return "No";
	}
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		ArrayList<Integer> list1 = new ArrayList<Integer>();

		for (int i = 0; i < n; i++) {
			int count = 0;
			if(sc.hasNextInt())
				 count = sc.nextInt();
			for (int j = 0; j < count; j++) {
				list1.add(sc.nextInt());
			}
			System.out.println(f(list1));
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值