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.

  • 相关阅读:
    c# 多线程系列二 自定义线程执行器
    博客人生
    c#实现分组服务器,单一无重复生成ID
    c# 游戏策划配置工具
    tar命令
    maven的一些使用技巧
    FSCapture截图工具
    删除已经跟踪的文件夹的版本控制
    idea模板的设置
    centos安装sublime
  • 原文地址:https://www.cnblogs.com/yiyi-xuechen/p/4425326.html
Copyright © 2011-2022 走看看