zoukankan      html  css  js  c++  java
  • leetcode1. Two Sum

    leetcode1.Two Sum

    题意:

    给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的值。

    您可以假设每个输入都只有一个解决方案,而您不能使用相同的元素两次。

    思路:

    O(n),遍历,每次将当前的值和下标存入字典,遍历到结果时,target-当前值 应该在字典中,然后直接返回两者下标。
    map的index为num[n],map的value为n

    ac代码:

    C++

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            vector<int>res;
            map<int,int> hash;
            for(int i = 0; i < nums.size(); i++)
            {
                if(hash.find(target-nums[i])!=hash.end())
                {
                    res.push_back(hash[target-nums[i]]);
                    res.push_back(i);
                    return res;
                }
                else
                {
                    hash[nums[i]]=i;
                }
            }
            return res;
        }
    };
    

    python

    class Solution:
        def twoSum(self, nums, target):
            """
            :type nums: List[int]
            :type target: int
            :rtype: List[int]
            """
            hash = {}
            for index,n in enumerate(nums):
                if target - n in hash:
                    return [hash[target - n], index]
                else:
                    hash[n] = index
            return []
    
  • 相关阅读:
    The library 'hostpolicy.dll' required to execute the application was not found in
    矩阵乘法
    2019-11-1
    四边形不等式的应用
    2019-10-30
    2019-10-29
    差分与前缀和
    平衡树SPLAY
    可爱的树链剖分(染色)
    cable tv network
  • 原文地址:https://www.cnblogs.com/weedboy/p/7143404.html
Copyright © 2011-2022 走看看