• Leetcode -- Two 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

    初始想法

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            int size = numbers.size();
            vector<int> ret;
            for (int i = 0; i < size; ++ i) {
                int j;
                for (j = 0; j < size; ++ j) {
                    int sum = numbers[i] + numbers[j];
                    if (sum == target) {
                        ret.push_back(i + 1);
                        ret.push_back(j + 1);
                        break;
                    }
                }
                if (j != size) {
                    return ret;
                }
            }
        }
    };

    结果超时,另想它法。

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            int size = numbers.size();
            vector<int> ret;
            map<int, int> hMap;
            for (int i = 0; i < size; ++ i) {
                if (!hMap.count(numbers[i])) { // return the numbers of numbers[i]
                    hMap.insert(pair<int, int>(numbers[i], i));
                }
                if (hMap.count(target - numbers[i])) {
                    int n = hMap[target-numbers[i]]; // return the index of target-numbers[i]
                    if (n < i) {
                        ret.push_back(n + 1);
                        ret.push_back(i + 1);
                        return ret;
                    }
                }
            }
            return ret;
        }
    };

    定义一个哈希表,key是numbers里面的数字numbers[i],record是数字的下标i;

    如果数字在哈希表中不存在,将该数字以及下标插入哈希表;

    在表中查找是否存在target - numbers[i],如果存在,并且它的下标小于n,则返回结果。

    不存在的情况下,返回结果为NULL.

  • 相关阅读:
    [LeetCode] Valid Palindrome
    [LeetCode] Word Ladder II(bfs、dfs)
    [LeetCode] Word Ladder
    [LeetCode] Longest Consecutive Sequence(DP)
    [LeetCode] Binary Tree Maximum Path Sum(递归)
    [LeetCode] Search in Rotated Sorted Array II
    hadoop streaming map输入文件路径获取
    LeetCode 4. 寻找两个正序数组的中位数
    剑指 Offer 56
    LeetCode 260.只出现一次的数字 III
  • 原文地址:https://www.cnblogs.com/yiyi-xuechen/p/4425326.html
Copyright © 2020-2023  润新知