题解 | #数据分类处理#
数据分类处理
http://www.nowcoder.com/practice/9a763ed59c7243bd8ab706b2da52b7fd
本来是使用的Map<Integer, ArrayList> 来存储的r对应的所有i下标及值
后来发现使用StringBuilder就可以直接进行结果的拼接了,代码如下
public class Main {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()){
// 获取I序列中元素个数并存储
int n = sc.nextInt();
int[] I = new int[n];
for (int i = 0; i < n; i++)I[i] = sc.nextInt();
// 获取R中元素个数并存储不重复元素
n = sc.nextInt();
TreeSet<Integer> R = new TreeSet<>();
for (int i = 0; i < n; i++) R.add(sc.nextInt());
// 统计最后输出元素个数
int count = 0;
StringBuilder res = new StringBuilder();
for (int r : R){
int t = 0;
StringBuilder temp = new StringBuilder();
for (int i = 0; i < I.length; i++){
if((I[i] + "").indexOf(r + "") != -1) {// 判断是否符合要求
temp.append(i).append(" ").append(I[i]).append(" ");
t++;
}
}
if (t > 0){// 存在I再进行添加
res.append(r).append(" ").append(t).append(" ").append(temp.toString());
count += (t * 2 + 2);
}
}
// 最后输出并换行
System.out.println(count + " " + res.toString());
}
}
}