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.

  • 相关阅读:
    php intval()函数
    MVC开发模式
    Session详解
    JSP入门
    Response中文乱码问题
    cookie入门
    idea实现更改servlet模板
    使用new和newInstance()创建类的区别
    Servlet 3.0 新特性详解
    web Servlet 3.0 新特性之web模块化编程,web-fragment.xml编写及打jar包
  • 原文地址:https://www.cnblogs.com/yiyi-xuechen/p/4425326.html
Copyright © 2011-2022 走看看