码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode

时间:2018-08-23 16:52:04      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:i++   order   def   and   leetcode   target   div   style   重复   

1、Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

思路:
关键词:一遍迭代map
建立map,迭代一遍数组,第一个迭代开始检查numToFind是否存在于map中。存在就返回两者的index;
不存在就把当前的数组nums[i]插入到map。重复迭代下去。

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

 

python:

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        maps={}
        for i in range(len(nums)):
            if target-nums[i] in maps:
                return i,maps[target-nums[i]]
            else:
                maps[nums[i]]=i
        return -1,-1

 



leetcode

标签:i++   order   def   and   leetcode   target   div   style   重复   

原文地址:https://www.cnblogs.com/hotsnow/p/9524309.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!