两个数组各自一个游标指针,按位添加到结果数组
注意第二行字符串可能为空串,关键空串Scanner读不到,需要判断是否有next
推荐一波stream流式编程,java玩出python的感觉。
package org.niuke.solution26; import java.util.Arrays; import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); String str = sc.nextLine(); if(!sc.hasNext()){ System.out.println(str); return; } String[] s1 = str.split(","); String[] s2 = sc.nextLine().split(","); int[] ints1 = Arrays.stream(s1).mapToInt(Integer::parseInt).toArray(); int[] ints2 = Arrays.stream(s2).mapToInt(Integer::parseInt).toArray(); int p1 = 0, p2 = 0; int[] s = new int[s1.length + s2.length]; while (p1 < ints1.length || p2 < ints2.length) { if(p1 < ints1.length && p2 < ints2.length){ if(ints1[p1] <= ints2[p2]){ s[p1 + p2] = ints1[p1]; p1++; }else{ s[p1 + p2] = ints2[p2]; p2++; } }else if(p1 < ints1.length){ s[p1 + p2] = ints1[p1]; p1++; }else{ s[p1 + p2] = ints2[p2]; p2++; } } for(int i = 0; i < s.length; i++){ if(i < s.length - 1){ System.out.print(s[i] + ","); }else{ System.out.print(s[i]); } } } }