1. 程式人生 > 其它 >Leetcode No.1 Two Sum(c++雜湊表實現)

Leetcode No.1 Two Sum(c++雜湊表實現)

1. 題目

1.1 英文題目

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

1.2 中文題目

給定一個整數陣列nums,返回陣列中“和是某個給定值target”的兩個數的下標。假設對於每次輸入有且只有一個解。

輸入輸出

輸入 輸出
nums = [2,7,11,15], target = 9 [0,1]
---- ----
nums = [3,2,4], target = 6 [1,2]
---- ----
nums = [3,3], target = 6 [0,1]

2. 實驗平臺

IDE:VS2019
IDE版本:16.10.1
語言:c++

3. 程式碼

3.1 功能程式

#pragma once
#include<vector>
#include<map>
using namespace std;

//主功能
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) 
    {
        map<int, int> hashMap; // 宣告雜湊表,儲存已經遍歷過的nums,其中nums的元素為key,元素的索引為value
        vector<int> ans; // 儲存結果
        for (int i = 0; i < nums.size(); i++) // 遍歷nums
        {
            int temp = target - nums[i]; // 定義target與nums[i]的差值
            if (hashMap.count(temp)) // 向前搜尋是否有與差值相同的元素,若有
            {
                ans = { hashMap[temp], i }; // 給出結果
            }
            hashMap[nums[i]] = i; // 將遍歷過的nums[i]加入到雜湊表hashMap中
        }
        return ans; // 返回結果
    }
};

3.2 測試程式

#include "Solution.h"
#include <vector>
#include<iostream>
using namespace std;

// 主程式
void main()
{
	vector<int> nums = { 1,1,2,7,4,2,5 };
	int target = 4; // 定義輸入
	Solution solution; // 例項化Solution
	vector<int> result = solution.twoSum(nums, target); // 主演算法
	cout << "[" << result[0] << "," << result[1] << "]" << endl; // 輸出結果
}

4. 程式碼思路

構建雜湊表,每次迴圈搜尋時,都從搜尋當前位置到前面幾個元素進行查詢

5. 注意事項

雜湊表會對相同的key值的value進行覆蓋處理,這一點需要加以注意。