题解 | #数据分类处理#

数据分类处理

https://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        // while (in.hasNextInt()) { // 注意 while 处理多个 case
        //     int a = in.nextInt();
        //     int b = in.nextInt();
        //     System.out.println(a + b);
        // }

        String line1 = in.nextLine();
        int ifirst = line1.indexOf(' ');
        int ilen = Integer.parseInt(line1.substring(0, ifirst));
        String[] I = line1.substring(ifirst + 1).split(" ");
        String line2 = in.nextLine();
        int rfirst = line2.indexOf(' ');
        int rlen = Integer.parseInt(line2.substring(0, rfirst));
        String[] R = line2.substring(rfirst + 1).split(" ");
	  
        sort(R);
        Node[] nodes = new Node[rlen];
        int index = 0;
        for (int i = 0; i < rlen; i++) {
            if (i > 0 && R[i].equals(R[i - 1])) {
                continue;
            }
            int count = 0;
            
            int[] containIndex = new int[ilen];
            boolean contains = false;
            for (int j = 0; j < ilen; j++ ) {
                if (I[j].contains(R[i])) {
                    containIndex[count] = j;
                    count++;
                    contains = true;
                }
            }
            if (contains) {
                Node node = new Node();
                node.containIndex = containIndex;
                node.count = count;
                node.r = R[i];
                nodes[index] = node;
                index++;
            } else {
                continue;
            }

        }
        int sum = 0;
        for (int i = 0; i < index; i++) {
            sum = sum + nodes[i].count * 2 + 2;
        }
        System.out.print(sum + " ");
        for (int i = 0; i < index; i++) {
            System.out.print(nodes[i].r + " " + nodes[i].count + " ");
            for (int j = 0; j < nodes[i].count; j++) {
                System.out.print(nodes[i].containIndex[j] + " " + I[nodes[i].containIndex[j]] +
                                 " ");
            }
        }
    }
    private static void sort(String [] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = i; j < arr.length; j++) {
                if (Integer.parseInt(arr[i]) > Integer.parseInt(arr[j])) {
                    String temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
    }
}

class Node {
    protected String r;
    protected int count;
    protected int[] containIndex;
}

全部评论

相关推荐

纸鹰:对他说:“你好,我是百度JAVA。”
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务