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

LeetCode 1. twoSums

时间:2015-06-02 00:20:56      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

C++:

vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int, int> hashMap;?        
    for (int i = 0; i < nums.size(); i++) {
            if(hashMap.find(nums[i]) == hashMap.end()){
                hashMap[target-nums[i]] = i;
            }else{
                return vector<int> {hashMap[nums[i]]+1, i+1};
            }
        }
    return vector<int> {};
}

1. hashMap[value] = i 使得value + nums[i] = target

2. unordered_map其内部存储为hash、遍历无序、使用需重载operator ==以及hash_value(), map存储为树、需重载operator <; 详见文章http://blog.csdn.net/orzlzro/article/details/7099231

3. hashMap[nums[i]]一定比i小,因前者值为几个迭代之前的i而这里i从小到大

Python:

def twoSum(self, nums, target):
        m_map = {}
        for i in range(len(nums)):
            if nums[i] not in m_map:
                m_map[target - nums[i]] = i
            else:
                return[m_map[nums[i]]+1, i+1]

讨论里有更简洁代码,

for j, item in enumerate(nums, 1): #start from 1 & items are entries
  i = m_map.get(item, -1) #the same as m_map[] but instead of crush, gives back -1 when couldn‘t find item
   if i > 0:
     return [i, j]
   m_map[target - item] = j

 

LeetCode 1. twoSums

标签:

原文地址:http://www.cnblogs.com/rangozhang/p/4545222.html

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