zoukankan      html  css  js  c++  java
  • leetcode148two-sum

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    题目描述

    给出一个整数数组,请在数组中找出两个加起来等于目标值的数,
    你给出的函数twoSum 需要返回这两个数字的下标(index1,index2),需要满足 index1 小于index2.。注意:下标是从1开始的
    假设给出的数组中只存在唯一解
    例如:

    给出的数组为 {2, 7, 11, 15},目标值为9
    输出 ndex1=1, index2=2

    示例1

    输入

    [3,2,4],6

    输出

    [2,3]
    //方法一 暴力

    //方法二 C++版本的两遍哈希表(官方题解)
    /*
    通过以空间换取速度的方式,我们可以将查找时间从 O(n) 降低到 O(1)。
    C++版本的哈希表算法采用unordered_map。
    */
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ans;
        unordered_map<int,int> tmpmap;
        int length = nums.size();
        for(int i = 0;i < length;i++){
            tmpmap[nums[i]] = i;
        }
        for (int i = 0; i < length; i++){
            if(tmpmap.count(target - nums[i]) != 0 && tmpmap[target - nums[i]] != i){  
            //使用count,返回的是被查找元素的个数。如果有,返回1;否则,返回0。
                ans.push_back(i);
                ans.push_back(tmpmap[target - nums[i]]);
                break;
            }
        }
        return ans;
    }

    //方法三 C++版本的一遍哈希表(官方题解)
    /*
    事实证明,我们可以一次完成。在进行迭代并将元素插入到表中的同时,我们还会回过头来检查
    表中是否已经存在当前元素所对应的目标元素。如果它存在,那我们已经找到了对应解,并立即将其返回。
    */
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ans;
        unordered_map<int,int> tmpmap;
        int length = nums.size();
        for (int i = 0; i < length; i++){
            if(tmpmap.count(nums[i]) != 0){
                ans.push_back(tmpmap[nums[i]]);
                ans.push_back(i);
                break;
            }
            tmpmap[target - nums[i]] = i;
        }
        return ans;
    }
    class Solution:
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            cache = {}
            for index,num in enumerate(nums):
                another_num = target-num
                if another_num in cache:
                    return [cache[another_num],index]
                cache[num]=index
            return None


  • 相关阅读:
    HTML5基础
    行为类型11-11:状态模式(State Pattern)
    行为类型11-10:中介者模式(MediatorPattern)
    行为类型11-9:责任链模式(Chain of Responsibility Pattern)
    行为类型11-8:模板模式(Template Pattern)
    行为类型11-7:命令模式(Command Pattern)
    行为类型11-6:解释器模式(Interpreter Pattern)
    FTP 连接失败,防火墙端口设置
    Windows下 NodeJs 版本管理 Nvm
    Ubuntu vi 方向键不正常问题
  • 原文地址:https://www.cnblogs.com/hrnn/p/13323008.html
Copyright © 2011-2022 走看看