Rust : codewars的Sum of Pairs

30 篇文章 0 订阅

还是见codewars的Sum of Pairs:

一、相关的要求

Given a list of integers and a single sum value, return the first two values (parse from the left please) in order of appearance that add up to form the sum.

sum_pairs([11, 3, 7, 5],         10)
#              ^--^      3 + 7 = 10
== [3, 7]

sum_pairs([4, 3, 2, 3, 4],         6)
#          ^-----^         4 + 2 = 6, indices: 0, 2 *
#             ^-----^      3 + 3 = 6, indices: 1, 3
#                ^-----^   2 + 4 = 6, indices: 2, 4
#  * entire pair is earlier, and therefore is the correct answer
== [4, 2]

sum_pairs([0, 0, -2, 3], 2)
#  there are no pairs of values that can be added to produce 2.
== None/nil/undefined (Based on the language)

sum_pairs([10, 5, 2, 3, 7, 5],         10)
#              ^-----------^   5 + 5 = 10, indices: 1, 5
#                    ^--^      3 + 7 = 10, indices: 3, 4 *
#  * entire pair is earlier, and therefore is the correct answer
== [3, 7]
Negative numbers and duplicate numbers can and will appear.

NOTE: There will also be lists tested of lengths upwards of 10,000,000 elements. Be sure your code doesn't time out.

二、我的解法

use std::collections::HashMap;
fn sum_pairs(ints: &[i8], s: i8) -> Option<(i8, i8)> {
    // your code
    let mut pair: HashMap<i64, Option<(i8, i8)>> = HashMap::new();
    let mut c = 0_i64;
    (&ints)
        .into_iter()
        .filter(|&x| {
            c += 1_i64;
            let mut indice = 0_64;
            (&ints[c as usize..])
                .into_iter()
                .filter(|&y| {
                    indice += 1_i64;
                    match (*y) as i64  + (*x) as i64 == s as i64 {
                        true => {
                            pair.insert(indice + c, Some((*x, *y)));
                            return true;
                        }
                        _ => return false,
                    }
                })
                .collect::<Vec<_>>()
                .len() > 0usize
        })
        .collect::<Vec<_>>();
    match pair.len() > 0 {
        true => {
            let mut indices: Vec<i64> = pair.keys().into_iter().map(|&x| x).collect();
            indices.sort();
            let min_indice = &indices.first().unwrap();
            //println!("pair:{:?}", pair);
            //println!("indices:{:?} min_indice :{:?}", indices, min_indice);
            return *(pair.get(&min_indice).unwrap());
        }
        _ => return None,
    }
}

通过了测试,问题是提交超时,有待优化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值