zoukankan      html  css  js  c++  java
  • 两数之和(Python and C++解法)

    题目:

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

    你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

    示例:

    给定 nums = [2, 7, 11, 15], target = 9

    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/two-sum

    思路:

      双重循环复杂度较高。可以借助字典结构,当遍历到某一数值num时,去查找(target-num)是否存在于字典中,该查询的时间复杂度是O(1)。

    Python题解:

     1 class Solution(object):
     2     @staticmethod  # two_sum方法不涉及对类属性的操作
     3     def two_sum(nums, target):
     4         num_store = dict()  # 存储key-value
     5         for i, num in enumerate(nums):
     6             if target - num in num_store:
     7                 return [i, num_store[target - num]]
     8             else:
     9                 num_store[num] = i  # 此处key是num,value是i,需要使用num定位其下标i
    10 
    11 if __name__ == '__main__':
    12     the_target = 9
    13     the_nums = [2, 7, 11, 15]
    14     s = Solution()
    15     result = s.two_sum(the_nums, the_target)
    16     print(result)  # [1, 0]

    C++题解:

     1 #include "pch.h"
     2 #include <iostream>
     3 #include <vector>
     4 #include <unordered_map>
     5 using namespace std;
     6 
     7 class Solution {
     8 public:
     9     vector<int> twoSum(vector<int> &nums, int target) {  // vector作为函数的参数或者返回值时需要注意:“&”绝对不能少
    10         unordered_map<int, int> hash;  // unordered_map底层是哈希表,查找效率较高
    11         vector<int> result;
    12         int numsSize = nums.size();
    13         for (int i = 0; i < numsSize; i++) {
    14             int numToFind = target - nums[i];
    15             if (hash.find(numToFind) != hash.end()) {  // 判断一个值是否在哈希表中的方法
    16                 result.push_back(i);
    17                 result.push_back(hash[numToFind]);
    18                 return result;
    19             }
    20             else
    21                 hash[nums[i]] = i;
    22         }
    23         //return result;  // leetcode上必须有这一行的返回结果
    24     }
    25 };
    26 
    27 int main() {
    28     int theTarget = 9;
    29     vector<int> theNums{2, 7, 11, 15};  // 初始化vector的方法
    30     Solution s;
    31     for (auto res: s.twoSum(theNums, theTarget)) {  // 打印vector的方法
    32         cout << res << " ";  // 1 0
    33     }
    34 }
  • 相关阅读:
    HTML的<head>中的内容总结
    毕业设计
    win7中protel99添加元件库
    E题
    D 题
    C 题 KMP中next[]问题
    B题 Sort the Array
    A题
    CSU1350 To Add which?
    CodeForce 448C 木片填涂问题
  • 原文地址:https://www.cnblogs.com/kongzimengzixiaozhuzi/p/12990301.html
Copyright © 2011-2022 走看看