美文网首页
『Rust刷算法』LeetCode1-两数之和

『Rust刷算法』LeetCode1-两数之和

作者: QianmianH | 来源:发表于2020-05-09 17:52 被阅读0次

要求

  • 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum

暴力穷举法

impl Solution {
    pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
        let mut res = Vec::<i32>::new();
        for i in 0..nums.len(){
            for j in (i+1)..nums.len(){
                if (target == nums[i]+nums[j]){
                    res.push(i as i32);
                    res.push(j as i32);
                }                
            }
        }
        res
    }
}

HashMap

use std::collections::HashMap;

impl Solution {
    pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
        let mut res = vec![];
        let mut cache = HashMap::new();

        for (index, item) in nums.iter().enumerate() {
            let sub = target - *item;

            match cache.get(item) {
                Some(pre_index) => {
                    res.push(*pre_index);
                    res.push(index as i32);
                    return res
                },
                None => {
                    cache.insert(sub, index as i32);
                },
            }
        }
        res
    }
}

| 方法 | 耗时 | 内存 |
|暴力法|36 ms|2.2 MB|
|HashMap|0ms|2.4MB|

相关文章

  • 『Rust刷算法』LeetCode1-两数之和

    要求 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回...

  • leetCode1-两数之和

    给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值的那两个 整数,并返回它们...

  • 两数之和 - Rust

    采用 HashMap 记录减少时间复杂度: 复杂度分析空间复杂度: O(N):主要是记录 hash 值。时间复杂度...

  • 算法刷题-两数之和

    八个Docker的真实应用场景 【编者的话】Flux 7介绍了常用的8个Docker的真实使用场景,分别是简化配置...

  • Swift刷算法:两数之和

    给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 ...

  • LeetCode1-两数之和(简单)

    原题 Given an array of integers, return indices of the two ...

  • 「算法」两数之和 & 两数之和 II

    00001 两数之和 题目描述 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只...

  • 算法:两数之和

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重...

  • 算法-两数之和

    这是一道LeetCode上的问题,详见两数之和,难度标注是简单,但是我思考到了一些比较复杂的情况,之后我会修改题目...

  • 算法--两数之和

    问题描述: 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样...

网友评论

      本文标题:『Rust刷算法』LeetCode1-两数之和

      本文链接:https://www.haomeiwen.com/subject/mwqlnhtx.html