题解 | #数据分类处理#

数据分类处理

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            int n1 = in.nextInt();
            //输入I序列
            int[] I = new int[n1];
            for (int i = 0; i < n1; i++) {
                I[i] = in.nextInt();
            }
            //输入R<i>序列
            int n2 = in.nextInt();
            int[] Ri = new int[n2];
            for(int i=0;i<n2;i++){
                Ri[i]=in.nextInt();
            }
            //排序
            Arrays.sort(Ri);
            //双指针去重
            int index = 0;
            for (int i = 0; i < n2; i++) {
                if (i == 0) {
                    Ri[index] = Ri[i];
                    index++;
                } else if (Ri[i] != Ri[index - 1]) {
                    Ri[index] = Ri[i];
                    index++;
                }    
            }
            //输出的数
            int count = 0;
            List<String> ans=new ArrayList<>();
            for (int i = 0; i < index; i++) {
                int r = Ri[i];
                //转String
                String base = String.valueOf(r);
                //判断包含
                int isContained = 0;
                //包含r的I个数
                int rCount=0;
                String res="";
                for (int j = 0; j < n1; j++) {
                    int num = I[j];
                    //转字符串
                    String s = String.valueOf(num);
                    int flag=0;
                    //替换子串,长度变化,说明包含base整体
                    String temp=s.replaceAll(base,"");
                    if(temp.length()==s.length()){
                        flag++;
                    }
                    if (flag == 0) {
                        isContained++;
                        rCount++;
                        //num包含了r,记下num的下标及其值,统计符合条件的num的数量
                        count += 2;
                        res=res+" "+j+" "+num;
                    }
                }
                if (isContained != 0) {
                    //被包含
                    count+=2;
                    res=r+" "+rCount+res;
                    ans.add(res);
                }
                // System.out.print(res);
                
            }
            System.out.print(count);
            for(String str:ans){
                System.out.print(" "+str);
            }
        }
    }
}

1个小时。。。。。。用到了双指针去重和排序

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务