2022-06-29:x = { a, b, c, d }, y = { e, f, g, h }, x、y两个小数组长度都是4。 如果有: a + e = b + f = c + g = d + h, 那么说x和y是一个完美对。 题目给定N个小数组,每个小数组长度都是K。 返回这N个小数组中,有多少完美对。 来自阿里。

答案2022-06-29:

找特征,存map,求数组相邻数字的差值,组装成key,value是数量。

代码用rust编写。代码如下:

use std::collections::HashMap;
fn main() {
    let sc: Vec<i32> = vec![5, 3, 2, 11, 21, 19, 10, 1, 20, 11, 1, 6, 15, 24, 18, 27, 36];
    let mut ii: i32 = 0;
    while ii < sc.len() as i32 {
        let n = sc[ii as usize];
        ii += 1;
        let m: i32 = sc[ii as usize];
        ii += 1;
        let mut matrix: Vec<Vec<isize>> = vec![];
        for i in 0..n {
            matrix.push(vec![]);
            for _ in 0..m {
                matrix[i as usize].push(sc[ii as usize] as isize);
                ii += 1;
            }
        }
        println!("matrix = {:?}", matrix);
        let ans = perfect_pairs(&mut matrix);
        println!("ans = {}", ans);
    }
}

fn perfect_pairs(matrix: &mut Vec<Vec<isize>>) -> isize {
    let mut ans: isize = 0;
    // key : 字符串 特征,差值特征 : "_5_-2_6_9"
    let mut counts: HashMap<String, isize> = HashMap::new();
    for arr in matrix.iter() {
        let mut self0: String = String::new();
        let mut minus: String = String::new();
        for i in 1..arr.len() as isize {
            self0.push_str(
                &(String::from("_") + &format!("{}", arr[i as usize] - arr[(i - 1) as usi***us.push_str(
                &(String::from("_") + &format!("{}", arr[(i - 1) as usize] - arr[i as usize])),
            );
        }
        ans += match counts.get(&minus) {
            Some(v) => *v,
            None => 0,
        };
        counts.insert(
            self0.clone(),
            match counts.get(&self0) {
                Some(v) => (*v) + 1,
                None => 1,
            },
        );
    }
    return ans;
}

执行结果如下:

在这里插入图片描述


左神java代码