用 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 协议》,转载必须注明作者和本文链接
比php ,java都繁琐点 :sob: 和go 一样
@qinplain 当你学完整个课程后就会发现这个其实也不难
@qinplain 刷题适合在学习完整个知识之后再进行。Rust和其它语言不大一样的地方就是,其它语言学一点就可以做点东西了,Rust必须要多学点,然后再来,要不然有些地方没弄懂,编译不过,因为Rust的编译器就做了很多检查,尽量减少你程序的bug。所以Rust是编译通过难,其它语言是编译容易,但是定位bug难。 就我个人而言,还是非常推荐学习Rust的。
还可以再优化下,or_insert 换成insert,已经是none就没必要再次判断是否存在key
@linghuyichong get的key和插入的key不一样哈,另外我当时是考虑一下假定结果有多种的情况,就以第一种为准,当然题中假定了只有一种输出,所以不用or_insert也是可以的