首页 > 其他分享 >[1] LeetCode 刷题笔记: 两数之和 [S]

[1] LeetCode 刷题笔记: 两数之和 [S]

时间:2023-01-08 22:44:17浏览次数:45  
标签:return target nums 复杂度 哈希 数组 LeetCode 两数 刷题

[1] LeetCode 刷题笔记: 两数之和 [S]

目录

题目描述

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

题解参考

暴力枚举

最容易想到的方法是枚举数组中的每一个数 x,寻找数组中是否存在 target - x

当我们使用遍历整个数组的方式寻找 target - x 时,需要注意到每一个位于 x 之前的元素都已经和 x 匹配过,因此不需要再进行匹配。而每一个元素不能被使用两次,所以我们只需要在 x 后面的元素中寻找 target - x

Algorithm [ 两数之和: 暴力枚举 ]
Input:  { nums /* array of integers */, target /* integer */ }
Output: { the position of two number in array `nums` }
-------------------------------
/* Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. */
Function EnumMethod
  For i <- 0 to nums.length
    For j <- i + 1 to nums.length
      If target = nums[i] + nums[j]
        Return [i, j]
      EndIf
    EndFor
  EndFor
EndFunction

复杂度分析

  • 时间复杂度:\(O(N^2)\),其中 \(N\) 是数组中的元素数量。最坏情况下数组中任意两个数都要被匹配一次。

  • 空间复杂度:\(O(1)\)。

使用哈希表

注意到方法一的时间复杂度较高的原因是寻找 target - x 的时间复杂度过高。因此,我们需要一种更优秀的方法,能够快速寻找数组中是否存在目标元素。如果存在,我们需要找出它的索引。

使用哈希表,可以将寻找 target - x 的时间复杂度降低到从 \(O(N)\) 降低到 \(O(1)\)。

这样我们创建一个哈希表,对于每一个 x,我们首先查询哈希表中是否存在 target - x,然后将 x 插入到哈希表中,即可保证不会让 x 和自己匹配。

Algorithm [ 两数之和: 哈希表 ]
Input:  { nums /* array of integers */, target /* integer */ }
Output: { the position of two number in array `nums` }
-------------------------------
/* Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. */
Function HashTableMethod
  hTable := HashTable::Init()
  For i <- 0 to nums.length
    AnotherFactorPosition = HashTable::find(hTable, target - nums[i])
    If AnotherFactorPosition is find
      Return [ AnotherFactorPosition, i ]
    hTable[nums[i]] = i
  EndFor
  Return []
EndFunction

复杂度分析

  • 时间复杂度:\(O(N)\),其中 \(N\) 是数组中的元素数量。对于每一个元素 \(x\),我们可以 \(O(1)\) 地寻找 target - x

  • 空间复杂度:\(O(N)\),其中 N 是数组中的元素数量。主要为哈希表的开销。

参考题解

C/C++ 的相关参考

C/C++ 的相关的代码
class Solution {
    struct Hashtable {};
    struct Enum {};
public:
    vector<int> twoSumImpl(Enum, vector<int>& nums, int target) {
        int n = nums.size();
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (nums[i] + nums[j] == target) {
                    return {i, j};
                }
            }
        }
        return {};
    }
    vector<int> twoSumImpl(Hashtable, vector<int>& nums, int target) {
        unordered_map<int, int> hashtable;
        for (int i = 0; i < nums.size(); ++i) {
            auto it = hashtable.find(target - nums[i]);
            if (it != hashtable.end()) {
                return {it->second, i};
            }
            hashtable[nums[i]] = i;
        }
        return {};
    }
    vector<int> twoSum(vector<int>& nums, int target) {
        return twoSumImpl(Hashtable(), nums, target);
    }
};

Rust 的相关参考

Rust 的相关的代码
use std::collections::HashMap;

impl HashTable for Solution {}

trait Enum {
    fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
        let (mut ret, nums_size) = ([0i32, 0i32], nums.len());
        for i in 0..nums_size {
            for j in i + 1 .. nums_size {
                if target == nums[i] + nums[j] {
                    ret[0] = i as i32; ret[1] = j as i32;
                    return ret.to_vec();
                }
            }
        }
        vec![]
    }
}

trait HashTable {
    fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
        if nums.len() < 2 {
            return vec![];
        }
        let mut position = HashMap::new();
        for i in 0 .. nums.len() {
            if position.contains_key(&nums[i])  {
                return vec![position[&nums[i]] as i32, i as i32]
            } else {
                position.insert(target - nums[i], i);
            }
        };
        vec![]
    }
}

标签:return,target,nums,复杂度,哈希,数组,LeetCode,两数,刷题
From: https://www.cnblogs.com/yvmg/p/17035506.html

相关文章

  • leetcode-230. 二叉搜索树中第K小的元素
    dfs中序遍历即可/***Definitionforabinarytreenode.*typeTreeNodestruct{*Valint*Left*TreeNode*Right*TreeNode*}*/var......
  • leetcode-671. 二叉树中第二小的节点
    dfs取左右子树第二大的值进行比较/***Definitionforabinarytreenode.*typeTreeNodestruct{*Valint*Left*TreeNode*Right*TreeNod......
  • leetcode-2185. 统计包含给定前缀的字符串
    简单题,重拳出击funcprefixCount(words[]string,prefstring)int{validCnt:=0for_,w:=rangewords{notValid:=falseiflen(w)......
  • leetcode-409-easy
    LongestPalindromeGivenastringswhichconsistsoflowercaseoruppercaseletters,returnthelengthofthelongestpalindromethatcanbebuiltwiththose......
  • leetcode-345-easy
    ReverseVowelsofaStringGivenastrings,reverseonlyallthevowelsinthestringandreturnit.Thevowelsare'a','e','i','o',and'u',andtheycan......
  • leetcode-643-easy
    MaximumAverageSubarrayIYouaregivenanintegerarraynumsconsistingofnelements,andanintegerk.Findacontiguoussubarraywhoselengthisequalto......
  • leetcode-496-easy
    NextGreaterElementIThenextgreaterelementofsomeelementxinanarrayisthefirstgreaterelementthatistotherightofxinthesamearray.Youar......
  • leetcode-521-easy
    LongestUncommonSubsequenceIGiventwostringsaandb,returnthelengthofthelongestuncommonsubsequencebetweenaandb.Ifthelongestuncommonsubseq......
  • leetcode-551-easy
    StudentAttendanceRecordIYouaregivenastringsrepresentinganattendancerecordforastudentwhereeachcharactersignifieswhetherthestudentwasab......
  • leetcode-485-easy
    MaxConsecutiveOnesGivenabinaryarraynums,returnthemaximumnumberofconsecutive1'sinthearray.Example1:Input:nums=[1,1,0,1,1,1]Output:3E......