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 []
    
  • 相关阅读:
    119. Pascal's Triangle II
    118. Pascal's Triangle
    112. Path Sum
    111. Minimum Depth of Binary Tree
    110. Balanced Binary Tree
    108. Convert Sorted Array to Binary Search Tree
    88. Merge Sorted Array
    83. Remove Duplicates from Sorted List
    70. Climbing Stairs
    陌陌面试经历
  • 原文地址:https://www.cnblogs.com/weedboy/p/7143404.html
Copyright © 2011-2022 走看看