前几天有幸在朋友的推荐下,面了一次巨硬。在丹棱街5号楼的17层会议室中,连续加班了两个月,每天平均睡五个小时的我,被几道算法题完全难住了。当时浆糊般的脑子里,只剩下了孤零零的递归想法,甚至连前几天才用过的std::priority_queue都完全想不起来了,只能傻乎乎的用std::sort完成。
所以,为了在以后能够更从容的去面试,早日脱离现在这种加班窘境,得强迫自己刷题了。同时,考虑到自己长期只使用c++这一门语言,需要扩展下眼界,刷题的这段时间,就决定使用rust了。希望自己能够坚持下来,最起码刷够200+以上的题目吧。
今天是第一天,就从第一道two sum开始吧。
题目如下:
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].
题目翻译:
输入一个整数数组和一个目标值,找到数组中两个值和为目标值,然后返回这两个值在数组中的位置,假设每一个输入都有解,并且唯一。
解题思路:
构建一个hash表,key值为数组中的项,value为位置。然后遍历数组,计算每一项与目标值的差值,并且在hash表中查找是否已经存在该差值,如果存在,则直接获取两个值的index,极为正确结果。
代码如下:
use std::collections::HashMap;
fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut v: Vec<i32> = Vec::new();
let mut m = HashMap::new();
for (index, value) in nums.iter().enumerate() {
let num = target - *value;
if m.contains_key(&num) {
return vec![m[&num], index as i32];
}
m.insert(value, index as i32);
}
return v;
}
#[test]
fn test_two_sum() {
let v = vec![2, 7, 11, 9];
let ans = two_sum(v, 9);
assert_eq!(ans[0], 0);
assert_eq!(ans[1], 1);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。