完美对
题目链接
其实规律在于ai-aj=-(bi-bj)
那么只需要一个map来存储这个序列的差并作为自己的code,用两个map统计优化,就能实现快速的查询
import java.util.*;
public class Main {
//设计获取反向code
public static String getAnti(String code){
StringBuilder s = new StringBuilder();
for(int i = 0;i<code.length();i++){
char c = code.charAt(i);
if(c == '+')
s.append('-');
else if(c=='-')
s.append('+');
else
s.append(c);
}
return s.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n, k;
n = scanner.nextInt();
k = scanner.nextInt();
int[][] array = new int[n][k];
for(int i = 0; i<n;i++){
for(int j = 0;j<k;j++){
array[i][j] = scanner.nextInt();
}
}
//负责统计相同的code有多少
Map<String,Integer> map = new HashMap<>();
//负责存自己的code
Map<Integer,String> imap = new HashMap<>();
int allSame = 0;
for (int i = 0; i < n; i++) {
int zeros = 0;
StringBuilder code = new StringBuilder();
for (int j = 0; j < k; j++) {
if(j!=0){
int a = array[i][j] - array[i][j-1];
if(a > 0){
code.append('+').append(a);
}
else if(a==0){
//特判0的情况 后面就不需要处理符号0了
code.append('.').append(a);
zeros ++;
}else{
code.append('-').append(Math.abs(a));
}
}
}
if(zeros == k-1)allSame++;//差值都是0才会匹配自己
imap.put(i,code.toString());
if(map.containsKey(code.toString())){
map.put(code.toString(),map.get(code.toString())+1);
}else{
map.put(code.toString(),1);
}
}
//统计匹配数
int res = 0;
for(int i = 0; i < n ;i++){
String code = imap.get(i);
String antiCode = getAnti(code);
if(map.containsKey(antiCode))
res += map.get(antiCode);
}
//最后得到的是总匹配数 要减掉每一项都是0的元素 再除以2
res -= allSame;//去掉匹配自己本身的
res /= 2;//匹配数除以2
System.out.println(res);
}
}
一次过,非常快乐