LeetCode 1——兩數之和

1. 題目

2. 解答

  • C++

遍歷數組,將數組中的元素和索引分別做爲 unordered_map 的鍵和值,若是目標值和當前元素的差已經存於在map 的鍵中,即找到結果。python

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        
        unordered_map<int, int> tabel;
        vector<int> index;
        int n = nums.size();
        for (int i = 0; i < n; i++)
        {
            int val = target - nums[i];
            
            if (tabel.count(val) == 1)
            {
                index.push_back(tabel[val]);
                index.push_back(i);
                return index;
            }
            else
            {
                tabel[nums[i]] = i;
            }
        }
    }
};
複製代碼
  • Python

遍歷數組,將數組中的元素和索引分別做爲字典的鍵和值,若是目標值和當前元素的差已經存於在字典的鍵中,即找到結果。數組

class Solution:
    def twoSum(self, nums, target):
        """ :type nums: List[int] :type target: int :rtype: List[int] """
        hash_table = {}       
        
        for index, value in enumerate(nums):
            
            num = target - value
            
            if num in hash_table:
                return [hash_table[num], index]
            
            hash_table[value] = index
複製代碼

獲取更多精彩,請關注「seniusen」! ui

相關文章
相關標籤/搜索