欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java面试题2

程序员文章站 2022-05-06 17:22:27
...

Question:
现有两个数组 A{“a1”,“a2”,“a3”…}、B{“b1”,“b2”,“b3”…};
按照a1,a2,b1,a3,a4,b2…的序列,返回一个***给定的长度n***的数组

/**
 * @author BadCode
 * @date 2019/9/28  22:07
 */
public class Demo {
    public static void main(String[] args) {
        String[] str1 = {"a1","a2","a3","a4","a5","a6","a7","a8","a9","a10"};
        String[] str2 = {"b1","b2","b3","b4","b5","b6","b7","b8","b9","b10"};
        String[] str3 = new String[str1.length + str2.length];
        method1(str1, str2, str3);
        for (String s : str3) {
            System.out.print(s + " ");
        }
    }

    private static void method1(String[] str1, String[] str2, String[] str3) {
        int count1= 0;
        int count2= 0;
        for (int i = 0; i < str3.length; i++) {
            if ((i + 1) % 3 != 0){
                if (count1 >= str1.length){
                    str3[i] = str2[count2];
                    count2++;
                    continue;
                }
                str3[i] = str1[count1];
                count1++;
            }else {
                if (count2 >= str2.length){
                    str3[i] = str1[count1];
                    count1++;
                    continue;
                }
                str3[i] = str2[count2];
                count2++;
            }
        }
    }
}

打印结果

//method1运行结果
a1 a2 b1 a3 a4 b2 a5 a6 b3 a7 a8 b4 a9 a10 b5 b6 b7 b8 b9 b10 

本博客是本人面试时遇到的问题,仅用来记录,欢迎前辈提出其中的错误或更好的建议。