2

【Rust3】实战笔记

 2 years ago
source link: https://www.guofei.site/2022/09/10/rust3.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【Rust3】实战笔记

2022年09月10日    Author:Guofei

文章归类: 语言    文章编号: 19002


版权声明:本文作者是郭飞。转载随意,但需要标明原文链接,并通知本人
原文链接:https://www.guofei.site/2022/09/10/rust3.html

Edit

vec 的遍历可以用 enumerate

for (idx, val) in vec1.iter().enumerate() {
idx as i32;
}

实战

这个抄的,& * 没搞懂

use std::collections::HashMap;
impl Solution {
    pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
        let mut map: HashMap<i32, i32> = HashMap::new();
        for (idx, n) in nums.iter().enumerate() {
            match map.get(&(target - *n)) {
                Some(&v) => return vec![v, idx as i32],
                None => map.insert(*n, idx as i32),
            };
        }
        vec![]
    }
}

下面这个自己写的

use std::collections::HashMap;
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
    let mut hash_map: HashMap<i32, i32> = HashMap::new();

    for (idx, val) in nums.iter().enumerate() {
        if hash_map.contains_key(&val) {
            return vec![hash_map[&val], idx as i32];
        }
        hash_map.insert(target - val, idx as i32);
    }

    return Vec::new();
}

您的支持将鼓励我继续创作!

qr.jpeg

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK