zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    Node.js 回调函数
    算法二、
    一、Perfect Squares 完全平方数
    Never Go Away
    python 内置方法
    web框架详解之tornado 三 url和分页
    web框架详解之tornado 二 cookie
    前端各种插件
    AJAX请求时status返回状态明细表
    LR之-参数化
  • 原文地址:https://www.cnblogs.com/yiyi-xuechen/p/4425326.html
Copyright © 2011-2022 走看看