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.

  • 相关阅读:
    [转]如何分析监控的关键指标
    性能测试指标&说明 [解释的灰常清楚哦!!]
    页面性能测试&提升方式
    转:使用 JMeter 完成常用的压力测试
    细雨学习笔记:JMeter 的主要测试组件总结
    压力测试了解
    影响性能的因素
    网址收藏
    Windows安装TensorFlow
    ionic常见问题及解决方案
  • 原文地址:https://www.cnblogs.com/yiyi-xuechen/p/4425326.html
Copyright © 2011-2022 走看看