1. 程式人生 > 其它 >Leetcode刷題筆記 1.兩數之和

Leetcode刷題筆記 1.兩數之和

技術標籤:leetcodeleetcodehash雜湊表

1.兩數之和

時間:2020年12月19日
知識點:雜湊表
題目連結:https://leetcode-cn.com/problems/two-sum/

題目
給定一個整數陣列 nums 和一個目標值 target,請你在該陣列中找出和為目標值的那 兩個 整數,並返回他們的陣列下標。

你可以假設每種輸入只會對應一個答案。但是,陣列中同一個元素不能使用兩遍。

示例:

給定 nums = [2, 7, 11, 15], target = 9
因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解法

  1. 這是一道很經典的雜湊表的題
  2. 根據答案,我們不僅需要知道這個數是多少,還需要知道他的索引
  3. 自然而然,我們可以用hash表去存,key是數的大小,value是數的索引
  4. 每次判斷這個數 是否能和hash表中的數結合成target 也就是target-這個數是否在hash表中出現
  5. 否則放進hash表中

程式碼

#include <stdio.h>
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
    vector<
int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> ump; for(int i = 0 ; i < nums.size();i++){ auto iter = ump.find(target - nums[i]); if(iter != ump.end()) return {iter->second,i}; ump[nums[
i]]=i; } return {}; } }; int main() { vector<int> nums{2,7,11,15}; Solution s; int target = 9; vector<int> ans = s.twoSum(nums, target); cout<<ans[0]<<" "<<ans[1]<<endl; return 0; }

今天也是愛zz的一天哦!