首页 > 试题广场 >

合并数组

[编程题]合并数组
  • 热度指数:15754 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
请实现一个函数,功能为合并两个升序数组为一个升序数组

输入的格式是用逗号隔开的数字。

数据范围:输入的字符串长度满足

输入描述:
输入有多个测试用例,每个测试用例有1-2行,每行都是以英文逗号分隔从小到大排列的数字


输出描述:
输出一行以英文逗号分隔从小到大排列的数组
示例1

输入

1,5,7,9
2,3,4,6,8,10

输出

1,2,3,4,5,6,7,8,9,10

备注:
不允许使用原生的 sort、concat 等函数
#include <iostream>
#include <vector>
using namespace std;
void transform(string str, vector<int>& vec);
int main(){

    string str1, str2;
    cin >> str1 >> str2;
    if(str1.size() == 0){
        cout << str2 << endl;
        return 0;
    }
    if(str2.size() == 0){
        cout << str1 << endl;
        return 0;
    }
    vector<int> arr1, arr2;
    transform(str1, arr1);
    transform(str2, arr2);
    int i = 0, j = 0;
    vector<int> res;
    while(i < arr1.size() && j < arr2.size()){
        if(arr1[i] < arr2[j]){
            res.push_back(arr1[i]);
            ++i;
        }else{
            res.push_back(arr2[j]);
            ++j;
        }
    }
    while(i < arr1.size()){
        res.push_back(arr1[i]);
        ++i;
    }
    while(j < arr2.size()){
        res.push_back(arr2[j]);
        ++j;
    }
    for(int i = 0; i < res.size() - 1; ++i){
        cout << res[i] << ",";
    }
    cout << res.back() << endl;
    return 0;
}
void transform(string str, vector<int>& vec){
    int temp = 0;
    for(int i = 0; i < str.size(); ++i){
        if(str[i] >= '0' && str[i] <= '9'){
            temp = temp * 10 + str[i] - '0';
        }else{
            vec.push_back(temp);
            temp = 0;
        }
    }
    vec.push_back(temp);
}
发表于 2019-07-09 19:11:12 回复(0)
/*
动态规划。
每次比较当前两个数组中最小的元素,更小的放入答案数组中。
细节处理:
要处理只有一行输入的情况。否则会卡80%,非法访问。
*/
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s1 = in.nextLine();
        if (!in.hasNext()) {
            System.out.println(s1);
            return;
        }
        String s2 = in.nextLine();
        String[] str1 = s1.split(",");
        String[] str2 = s2.split(",");
        int len1 = str1.length;
        int len2 = str2.length;
        int[] arr1 = new int[len1];
        int[] arr2 = new int[len2];
        for (int i = 0; i < len1; i++) {
            arr1[i] = Integer.parseInt(str1[i]);
        }
        for (int i = 0; i < len2; i++) {
            arr2[i] = Integer.parseInt(str2[i]);
        }
        int[] ans = new int[len1 + len2];
        int loc1 = 0;
        int loc2 = 0;
        int loc = 0;
        for (loc = 0; loc < len1 + len2; loc++) {
            if (loc1 ==len1) {
                ans[loc] = arr2[loc2];
                loc2++;
            } else if (loc2 == len2) {
                ans[loc] = arr1[loc1];
                loc1++;
            } else if (arr1[loc1] < arr2[loc2]) {
                ans[loc] = arr1[loc1];
                loc1++;
            } else {
                ans[loc] = arr2[loc2];
                loc2++;
            }
        }
        for (int i = 0; i < len1 + len2 - 1; i++) {
            System.out.print(ans[i] + ",");
        }
        System.out.println(ans[len1 + len2 - 1]);
    }
}

发表于 2019-06-28 15:08:24 回复(1)
#include<iostream>
#include<vector>
#include<string>
#include<sstream>
using namespace std;
void func(vector<int>& nums1,vector<int>& nums2){
    int i=0;
    int j=0;
    int n1 = nums1.size();
    int n2 = nums2.size();
    while(i<n1&&j<n2){
        if(nums1[i]<=nums2[j]){
            cout<<nums1[i++]<<",";
        }else{
            cout<<nums2[j++]<<",";
        }
    }
    while(i<n1){
        cout<<nums1[i];
        if(i!=n1-1){
            cout<<",";
        }
        i++;
    }
    while(j<n2){
        cout<<nums2[j];
        if(j!=n2-1){
            cout<<",";
        }
        j++;
    }
}
int main(){
    string str1,str2;
    //这个getline是<string>中的函数,将一行的内容读取到字符串中
    getline(cin,str1);
    getline(cin,str2);
    if(str2.empty()){//如果只有一行,直接输出即可,不用考虑合并
        cout<<str1<<endl;
        return 0;
    }
    vector<int> nums1;
    vector<int> nums2;
    //将里面的逗号全部替换成为空格
    for(int i=0;i<str1.size();i++){
        if(str1[i]==','){
            str1[i]=' ';
        }
    }
    for(int i=0;i<str2.size();i++){
        if(str2[i]==','){
            str2[i]=' ';
        }
    }
    stringstream ss1(str1);
    int temp;
    while(ss1>>temp){
        nums1.push_back(temp);
    }
    stringstream ss2(str2);
    while(ss2>>temp){
        nums2.push_back(temp);
    }
    func(nums1,nums2);
    return 0;
}


发表于 2019-10-09 17:24:24 回复(0)
#include<bits/stdc++.h>
using namespace std;
int main(){
    string str1, str2;
    cin >> str1 >> str2;
    vector<int> arr;
    istringstream ss1(str1);
    int i;
    char c;
    while(ss1 >> i){
        arr.push_back(i);
        if(ss1 >> c ){
            continue;
        }
    }
    istringstream ss2(str2);
    while(ss2 >> i){
        arr.push_back(i);
        if(ss2 >> c ){
            continue;
        }
    }
    sort(arr.begin(), arr.end());
    cout << arr[0];
    for(int i = 1; i < (int)arr.size(); i++){
    	cout << "," << arr[i];
    }
    return 0;
}

发表于 2019-08-30 17:10:55 回复(1)
import java.util.*;
public class Main{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        String s1 = in.nextLine();
        if (!in.hasNext()) {
            System.out.println(s1);
            return;
        }
        String s2 = in.nextLine(); 
        String[] ss1 = s1.split(",");
        String[] ss2 = s2.split(",");
        int[] a = new int[ss1.length];
        int[] b = new int[ss2.length];
        for(int i = 0; i < ss1.length; i++) {
            a[i] = Integer.valueOf(ss1[i]);
        }
        for(int i = 0; i < ss2.length; i++) {
            b[i] = Integer.valueOf(ss2[i]);
        }
        int[] res = new Solution().merge(a,b);
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < res.length; i++) {
            sb.append(res[i]);
            if(i < res.length - 1) sb.append(",");
        }
        System.out.println(sb.toString());
        
    }
   
}
class Solution{
    public int[] merge(int[] a, int[] b) {
        int[] res = new int[a.length + b.length];
        int j = 0;
        for(int i = 0; i < a.length; i++) {
            res[j] = a[i];
            j++;
        }
        for(int i = 0; i < b.length; i++) {
            res[j] = b[i];
            j++;
        }
        quickSort(res, 0, res.length - 1);
        return res;
    }
    private static void quickSort(int[] a, int left, int right) {
        int l = left, r = right;
        if (l < r) {
            int key = a[left];
            while (l < r) {
                while (l < r && a[r] >= key) r--;
                if (l < r) a[l++] = a[r];
                while (l < r && a[l] < key) l++;
                if (l < r) a[r--] = a[l];
            }
            a[l] = key;
            quickSort(a, left + 1, right);
            quickSort(a, left, right - 1);
        }
    }
}

发表于 2021-06-01 15:13:28 回复(0)
非常朴素的做法:
分割字符串得到数组,然后进行合并。
需要注意的一点是第二次输入可能是空的字符串,需要做下判断
#include <iostream>
using namespace std;

int main(){
    //1,5,7,9
    string a;
    string b;
    vector<int> A;
    vector<int> B;
    cin >> a;
    char div = ','; //分隔符
    while(a.find_first_of(div) != string::npos){
        int pos = a.find_first_of(div);
        string str = "";
        for(int i = 0; i < pos; ++i){
            str += a[i];
        }
        A.push_back(atoi(str.c_str()));
        a = a.substr(pos + 1);
    }
    string str = "";
    for(int i = 0; i < a.length(); ++i){
        str += a[i];
    }
    A.push_back(atoi(str.c_str()));

    cin >> b;
     //因为第二次输入的字符串有可能为空,所以要做下判断
    if(b.length()) {
        while(b.find_first_of(div) != string::npos){
            int pos = b.find_first_of(div);
            string str = "";
            for(int i = 0; i < pos; ++i){
                str += b[i];
            }
            B.push_back(atoi(str.c_str()));
            b = b.substr(pos + 1);
        }
        str = "";
        for(int i = 0; i < b.size(); ++i){
            str += b[i];
        }
        B.push_back(atoi(str.c_str()));
    }
    //合并
    vector<int> merge;
    int Alen = A.size();
    int Blen = B.size();
    int i = 0, j = 0;
    while(i < Alen && j < Blen){
        if(A[i] < B[j]){
            merge.push_back(A[i]);
            ++i;
        } else {
            merge.push_back(B[j]);
            ++j;
        }
    }
    while(i < Alen){
        merge.push_back(A[i++]);
    }
    while(j < Blen){
        merge.push_back(B[j++]);
    }
    for(int i = 0; i < merge.size(); ++i){
        if(i == merge.size() - 1){
            cout << merge[i] << endl;
            return 0;
        }
        cout << merge[i] << ',';
    }
    return 0;
}


编辑于 2020-05-25 20:18:56 回复(0)
#include <bits/stdc++.h>
using namespace std;

int main(){
    int x;
    char c;
    string s;
    cin>>s;
    stringstream ss1(s);
    vector<int> a,b,v;
    while(ss1>>x){
        a.push_back(x);
        if(ss1>>c)
            continue;
    }
    cin>>s;
    if(cin.peek()==EOF){
        for(int i=0;i<a.size();i++){
            if(i==a.size()-1)
                cout<<a[i]<<endl;
            else
                cout<<a[i]<<",";
        }
        return 0;
    }
    stringstream ss2(s);
    while(ss2>>x){
        b.push_back(x);
        if(ss2>>c)
            continue;
    }
    int n = a.size(), m = b.size(), i=0, j=0;
    while(i<n&& j<m){
        if(a[i]<b[j])
            v.push_back(a[i++]);
        else if(a[i]>b[j])
            v.push_back(b[j++]);
    }
    while(i<n)
        v.push_back(a[i++]);
    while(j<m)
        v.push_back(b[j++]);
    for(int i=0;i<v.size();i++){
        if(i==v.size()-1)
            cout<<v[i]<<endl;
        else
            cout<<v[i]<<",";
    }

    return 0;
}

发表于 2019-12-10 09:37:27 回复(0)
#include <bits/stdc++.h>
using namespace std;
int main(){
    int num;
    vector<int> arr1,arr2;
    do{
        cin>>num;
        arr1.push_back(num);
    }
    while(cin.get()!='\n');
    
//80%卡在这里!!!要处理只有一行输入用cin.peek()判断是不是输入结尾;
    if(cin.peek()==EOF){             for(int i:arr1){             cout<<i;             if(i!=arr1.back())                 cout<<',';         }         return 0;     }     do{         cin>>num;         arr2.push_back(num);     }     while(cin.get()!='\n');     int i=0,j=0;     while(i!=arr1.size()&&j!=arr2.size()){         if(arr1[i]<=arr2[j])             cout<<arr1[i++];         else             cout<<arr2[j++];         if(i!=arr1.size()||j!=arr2.size())             cout<<',';     }     while(j!=arr2.size()){         cout<<arr2[j++];         if(j!=arr2.size())             cout<<',';     }     while(i!=arr1.size()){         cout<<arr1[i++];         if(i!=arr1.size())             cout<<',';     } }

编辑于 2019-12-06 20:23:13 回复(0)
import sys
a=list(map(int,sys.stdin.readline().split(',')))
try:
    b=list(map(int,sys.stdin.readline().split(',')))
    res=[]
    l,r=0,0
    while l<len(a) and r<len(b):
        if a[l]<b[r]:
            res.append(a[l])
            l+=1
        else:
            res.append(b[r])
            r+=1
    if r<len(b):
        res.extend(b[r:])
    else:
        res.extend(a[l:])
    res=list(map(str,res))
    print(','.join(res))
except:
    a=list(map(str,a))
    print(','.join(a))

编辑于 2019-08-14 13:54:03 回复(0)
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String str1 = scanner.next();
        if (!scanner.hasNext()) {
            System.out.println(str1);
            return;
        }
        int[] num1 = strToIntArr(str1);
        int[] num2 = strToIntArr(scanner.next());
        int[] num = new int[num1.length + num2.length];
        int index1 = 0, index2 = 0, index = 0;
        while (index1 < num1.length && index2 < num2.length) {
            num[index++] = (num1[index1] <= num2[index2]) ? num1[index1++] : num2[index2++];
        }
        while (index1 < num1.length) {
            num[index++] = num1[index1++];
        }
        while (index2 < num2.length) {
            num[index++] = num2[index2++];
        }
        for (int i = 0; i < num.length; i++) {
            if (i == num.length - 1) {
                System.out.println(num[i]);
            } else {
                System.out.print(num[i] + ",");
            }
        }
    }

    public static int[] strToIntArr(String str) {
        String[] strNumber = str.split(",");
        int[] number = new int[strNumber.length];
        for (int i = 0; i < strNumber.length; i++) {
            number[i] = Integer.parseInt(strNumber[i]);
        }
        return number;
    }
}
编辑于 2019-07-02 11:00:34 回复(0)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        String line1 = bf.readLine();
        String line2 = bf.readLine();
        //注意题目的输入为1-2行
        if (line2 == null){
            System.out.println(line1);
            return;
        }
        String[] strs1 = line1.split(",");
        String[] strs2 = line2.split(",");
        StringBuilder sb = new StringBuilder();
        //定义两个指针,每次添加较小的元素,并移动相应的指针,直到有一个指针到头了,把剩下的元素全部添加即可。
        int p1 = 0, p2 = 0;
        while (p1 < strs1.length && p2 < strs2.length) {
            if (Integer.parseInt(strs1[p1]) < Integer.parseInt(strs2[p2])) {
                sb.append(strs1[p1++]);
            } else {
                sb.append(strs2[p2++]);
            }
            sb.append(",");
        }
        while (p1 < strs1.length){
            sb.append(strs1[p1++]).append(",");
        }
        while (p2 < strs2.length){
            sb.append(strs2[p2++]).append(",");
        }
        System.out.println(sb.substring(0,sb.length()-1).toString());
    }
}
发表于 2019-08-05 08:48:42 回复(0)
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        //只有一行的话直接return
        String str = in.nextLine();
        String str1[] = str.split(",");
        try {
            //第二行可能不存在
            String str2[] = in.nextLine().split(",");
            int[] arr1 = new int[str1.length];
            int[] arr2 = new int[str2.length];

            for (int i = 0 ; i < str1.length; i++) {
                arr1[i] = Integer.parseInt(str1[i]);
            }
            for (int i = 0; i < str2.length; i++) {
                arr2[i] = Integer.parseInt(str2[i]);
            }
            int[] arr3 = merge(arr1, arr2);
            for (int i = 0; i < arr3.length - 1; i++) {
                System.out.print(arr3[i] + ",");
            }
            System.out.print(arr3[arr3.length - 1]);
        } catch (Exception e) {
            System.out.print(str);
        }


    }

    public static int[] merge(int[] arr1, int[] arr2) {
        int len1 = arr1.length;
        int len2 = arr2.length;
        int[] res = new int[len1 + len2];
        //arr1的指针
        int i = 0;
        //arr2的指针
        int j = 0;
        //放res的指针
        int z = 0;
        //放较小的值
        int tem = 0;
        while (i < len1 && j < len2) {
            if (arr1[i] < arr2[j]) {
                tem = arr1[i++];
            } else {
                tem = arr2[j++];
            }
            res[z++] = tem;
        }
        while (i < len1) {
            res[z++] = arr1[i++];
        }
        while (j < len2) {
            res[z++] = arr2[j++];
        }
        return res;
    }
}


发表于 2023-05-26 14:27:46 回复(0)
package main

import (
    "fmt"
    "os"
    "bufio"
    "strings"
    "strconv"
)

var in=bufio.NewReader(os.Stdin)

func main() {
    s1,_:=in.ReadString('\n')
    s2,ok:=in.ReadString('\n')
    if ok!=nil{
        fmt.Print(s1[:len(s1)-1])
        return
    }
    s1=s1[:len(s1)-1]
    s2=s2[:len(s2)-1]
    arr1:=strings.Split(s1,",")
    arr2:=strings.Split(s2,",")
    arr:=[]int{}
    for _,s:=range append(arr1,arr2...){
        x,_:=strconv.Atoi(s)
        arr=append(arr,x)
    }
    for i:=0;i<len(arr);i++{
        min:=i
        for j:=i+1;j<len(arr);j++{
            if arr[j]<arr[min]{
                min=j
            }
        }
        if min!=i{
            arr[min],arr[i]=arr[i],arr[min]
        }
    }
    for i,x:=range arr{
        fmt.Printf("%v",x)
        if i<len(arr)-1{
            fmt.Print(",")
        }
    }
}

发表于 2023-03-22 17:11:03 回复(0)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// [计] 分界符
const char* const DELIMITER = ",";

// ====================== function definition ======================
void printNumbers(int nums[], const int numsSize) {
  int i;
  for (i = 0; i < numsSize; ++i) {
    printf("%d", *(nums + i));
    if (i < numsSize - 1) putchar(',');
  }
  putchar('\n');
}

// conversion function
void readNumbers(const char* str, int* nums, int* size) {
  char* tok = strtok(str, DELIMITER);
  while (tok) {
    *(nums + (*size)++) = atoi(tok);
    tok = strtok(NULL, DELIMITER);
  }
}

void merge(int nums1[], int nums1Size, int nums2[], int nums2Size, int merged[]) {
  int i = 0, j = 0, k = 0;
  while (i < nums1Size && j < nums2Size)
    merged[k++] = nums1[i] < nums2[j] ? nums1[i++] : nums2[j++];
  
  while (i < nums1Size) merged[k++] = nums1[i++];
  while (j < nums2Size) merged[k++] = nums2[j++];
}
// ====================== function definition ======================

int main(const int argc, const char** argv) {
  
  char str1[2000], str2[2000];
  int nums1[500],  nums2[500], nums1Size, nums2Size;
  
  // handle input
  while (scanf("%s%s", str1, str2) != EOF) {
    
    nums1Size = nums2Size = 0;
    readNumbers(str1, nums1, &nums1Size);
    readNumbers(str2, nums2, &nums2Size);
    
    int merged[nums1Size + nums2Size];
    merge(nums1, nums1Size, nums2, nums2Size, merged);
    
    printNumbers(merged, nums1Size + nums2Size);
  }
  
  return 0;
}

发表于 2021-07-07 08:39:08 回复(0)
题目本身很简单,但是每次都要处理这个输入输出你们真的觉得不是在浪费时间吗?
Scanner scanner = new Scanner(System.in);
String a = scanner.nextLine();
if (!scanner.hasNextLine()) {
    System.out.println(a);
    scanner.close();
    return;
}
String[] nums1List = a.split(",");
String[] nums2List = scanner.nextLine().split(",");
scanner.close();
我写合并的时间不到10分钟,为了这几行代码花了20分钟,突然要在牛客上面试,这个好别扭啊,感觉面试凉了。
发表于 2020-07-15 21:58:54 回复(0)
import sys

in_list1 = sys.stdin.readlines()
if len(in_list1)==1:
    print(in_list1[0].strip())
else:
    list1 = [int(i) for i in in_list1[0].strip().split(',')]
    list2 = [int(j) for j in in_list1[1].strip().split(',')]
    final_list = list1 + list2
    final_list.sort()
    fin = [str(k) for k in final_list]
    res = ','.join(fin)
    print(res)
发表于 2020-06-10 17:14:01 回复(0)
#include <bits/stdc++.h>
using namespace std;
int main()
{
    vector<int> number;
    while(1)
    {
    	int t;
    	cin>>t;
    	number.push_back(t);
    	if(getchar()=='\n')
    	{
    		break;
		}
	}
	int t;
	while(cin>>t)
	{
		number.push_back(t);
		if(getchar()=='\n')
		{
			break;
		}
	}
    for(int i=0;i<number.size();i++)
    {
    	for(int j=i+1;j<number.size();j++)
    	{
    		if(number[i]>number[j])
    		{
    			int tmp=number[i];
    			number[i]=number[j];
    			number[j]=tmp;
			}
		}
	}
	for(int i=0;i<number.size();i++)
	{
		if(i<=number.size()-2)
		cout<<number[i]<<",";
		else
		cout<<number[i];
	}
    return 0;
}



弄到一个vector中,冒泡排序
发表于 2020-05-29 18:39:40 回复(0)
利用归并排序的核心思想,将两行String放到两个vector中,进而进行比较,将小的值转换成String,再添加到result即可
#include<iostream>
(720)#include<vector>
#include<string>
(765)#include<algorithm>
using namespace std;
void Push(vector<int>& a,string s){
    int temp=0;
    for(int i=0;i<s.size();++i){
        if(s[i]==',') {
            a.push_back(temp);
            temp=0;}
        else{
            temp*=10;
            temp+=(s[i]-'0');
        }
    }
    a.push_back(temp);
}
void PushToStr(string& result,int a){
   
    string res;
    if(a==0)
        res+='0';
    while(a){
        int temp=a%10;
        a/=10;
        res+=(temp+'0');
    }
    reverse(res.begin(),res.end());
    result+=res;
}
int main(){
    string str1,str2;
    getline(cin,str1);
    getline(cin,str2);
    vector<int> a;
    vector<int> b;
    if(str1.size()>0)
    Push(a,str1);
    if(str2.size()>0)
    Push(b,str2);
    int index1=0,index2=0;
    string result;
    while(index1<a.size()&&index2<b.size()){
        if(a[index1]<=b[index2]){
            PushToStr(result,a[index1]);
            index1++;
        }
        else{
            PushToStr(result,b[index2]);
            index2++;
        }
        result+=',';
    }
    while(index1<a.size()){
        PushToStr(result,a[index1++]);
        result+=',';
    }
    while(index2<b.size()){
        PushToStr(result,b[index2++]);
        result+=',';
    }
    result.pop_back();
    cout<<result<<endl;
}

发表于 2020-05-06 19:17:23 回复(0)
方法:创建一个长度为两个数组长度和的res数组,取两个指针用来遍历两个数组,指针起始都为0,每次比较对应位置把小的数加入res,并且把加入的指针向后移动一位,直到两个指针都移到末尾。时间复杂度O(m+n),空间复杂度O(m+n)
import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String tmp1 = sc.nextLine();
        if(!sc.hasNextLine()){
            System.out.print(tmp1);
            return;
        }
        String tmp2 = sc.nextLine();
        String[] s1 = tmp1.split(",");
        String[] s2 = tmp2.split(",");
        int[] nums1 = new int[s1.length];
        int[] nums2 = new int[s2.length];
        for(int i=0; i<s1.length; i++){
            nums1[i] = Integer.parseInt(s1[i]);
        }
        for(int i=0; i<s2.length; i++){
            nums2[i] = Integer.parseInt(s2[i]);
        }
        int[] res = new int[s1.length+s2.length];
        int p1 = 0, p2 = 0, index = 0;
        while(p1!=nums1.length || p2!=nums2.length){
            if(p1 == nums1.length){
                res[index] = nums2[p2];
                p2++;
            }
            else if(p2 == nums2.length){
                res[index] = nums1[p1];
                p1++;
            }
            else{
                if(nums1[p1]>=nums2[p2]){
                    res[index] = nums2[p2];
                    p2++;
                }
                else{
                    res[index] = nums1[p1];
                    p1++;
                }
            }
            index++;
        }
        for(int i=0 ; i<res.length; i++){
            System.out.print(res[i]);
            if(i!=res.length-1) System.out.print(",");
        }
    }
}


发表于 2020-05-05 06:17:55 回复(0)
其实就是合并两个有序数组,这种写法可以合并多行
import java.util.Scanner;

/**
 * @Date: 2020-04-29 22:25
 * @version: 1.0
 */
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String strs1[] = sc.nextLine().split(",");
        int arr1[] = new int[strs1.length];
        for (int i = 0;i<arr1.length;i++)
            arr1[i] = Integer.valueOf(strs1[i]);
        while (sc.hasNextLine()){
            String strs2[] = sc.nextLine().split(",");
            int arr2[] = new int[strs2.length];
            for (int j = 0;j<strs2.length;j++)
                arr2[j] = Integer.valueOf(strs2[j]);
            arr1 = merge(arr1,arr2);
        }
        for (int i=0;i<arr1.length-1;i++)
            System.out.print(arr1[i]+",");
        System.out.print(arr1[arr1.length-1]);
        sc.close();
    }

    private static int[] merge(int[] arr1, int[] arr2) {
        int arr[] = new int[arr1.length+arr2.length];
        int index = 0;
        int index1=0;
        int index2=0;
        while (index1<arr1.length&&index2<arr2.length){
            if (arr1[index1]<=arr2[index2])
                arr[index++]=arr1[index1++];
            else
                arr[index++]=arr2[index2++];
        }
        while (index1<arr1.length)
            arr[index++]=arr1[index1++];
        while (index2<arr2.length)
            arr[index++]=arr2[index2++];
        return arr;
    }
}

发表于 2020-04-29 22:58:58 回复(0)