用 Rust 刷 leetcode 第一题

problem

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Solution

use std::collections::HashMap;
impl Solution {
    pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
        let mut mm: HashMap<i32, i32> = HashMap::new();
        for (i, v) in nums.iter().enumerate() {
            match mm.get(&(target-v)) {
                Some(&index) => { return vec![index, i as i32]; }
                None => { mm.entry(*v).or_insert(i as i32); }
            }
        }
        vec![]
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
令狐一冲
讨论数量: 5

比php ,java都繁琐点 :sob: 和go 一样

4年前 评论

@qinplain 当你学完整个课程后就会发现这个其实也不难

4年前 评论

@qinplain 刷题适合在学习完整个知识之后再进行。Rust和其它语言不大一样的地方就是,其它语言学一点就可以做点东西了,Rust必须要多学点,然后再来,要不然有些地方没弄懂,编译不过,因为Rust的编译器就做了很多检查,尽量减少你程序的bug。所以Rust是编译通过难,其它语言是编译容易,但是定位bug难。     就我个人而言,还是非常推荐学习Rust的。

4年前 评论

还可以再优化下,or_insert 换成insert,已经是none就没必要再次判断是否存在key

match mm.get(&(v)) {
    Some(&index) => { return vec![index, i as i32]; }
    None => { mm.insert(target-v, i as i32); println!("{:?}", mm);}
}
4年前 评论

@linghuyichong get的key和插入的key不一样哈,另外我当时是考虑一下假定结果有多种的情况,就以第一种为准,当然题中假定了只有一种输出,所以不用or_insert也是可以的

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
文章
255
粉丝
120
喜欢
308
收藏
128
排名:335
访问:2.8 万
私信
所有博文
社区赞助商