首页 > 其他 > 详细

LeetCode 1. twoSums

时间:2015-06-02 00:18:35      阅读:139      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!