1. 程式人生 > 其它 >(十)資料結構(C++實現)

(十)資料結構(C++實現)

演算法與資料結構刷題系列之資料結構,僅記錄個人刷題總結記錄,方便複習。

雜湊表

兩數之和

Leetcode:https://leetcode-cn.com/problems/two-sum/

1.問題描述

​ 給定一個整數陣列,已知有且只有兩個數的和等於給定值,求這兩個數的位置。

2.輸入輸出

  • Input:nums = [2, 7, 11, 15],target = 9
  • Output:[0, 1]

3.演算法分析

利用雜湊表儲存遍歷過的值以及它們的位置,每次遍歷到位置i的時候,查詢雜湊表裡是否存在target-nums[i],若存在,說明這兩個值得和為target。

4.程式設計實現

#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> hash;        
        vector<int> ans;                
        for (int i = 0; i < nums.size(); i++) {            
            int num = nums[i];            
            auto pos = hash.find(target - num);                        
            if (pos == hash.end()) {                
                hash[num] = i;            
            } else {                
                ans.push_back(pos->second);                
                ans.push_back(i);                
                break;            
            }        
        }                
        return ans;    
    }
};
int main() {    
    Solution sol;    
    vector<int> nums;    
    int value, target;     
    getchar();
    while (cin >> value) {        
        nums.push_back(value);        
        if (cin.get() == ']') break;    
    }        
    cin >> target;        
    vector<int> ans = sol.twoSum(nums, target);    
    cout << ans[0] << " " << ans[1] << endl;    
    return 0;
}

本文為博主原創文章,未經博主允許禁止轉載,需轉載請註明出處,歡迎指正!