• 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


  • 相关阅读:
    Makefile 常用函数表
    情绪管理
    网赚呓语
    Gym 100952C&&2015 HIAST Collegiate Programming Contest C. Palindrome Again !!【字符串,模拟】
    Gym 100952B&&2015 HIAST Collegiate Programming Contest B. New Job【模拟】
    Gym 100952A&&2015 HIAST Collegiate Programming Contest A. Who is the winner?【字符串,暴力】
    HDU 1024 Max Sum Plus Plus【动态规划求最大M子段和详解 】
    HDU 1003 Max Sum【动态规划求最大子序列和详解 】
    HDU 1010 Tempter of the Bone【DFS经典题+奇偶剪枝详解】
    DFS中的奇偶剪枝学习笔记
  • 原文地址:https://www.cnblogs.com/hrnn/p/13323008.html
Copyright © 2020-2023  润新知