zoukankan      html  css  js  c++  java
  • LeetCode#1.Two Sum

    题目

    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

    You may assume that each input would have exactly one solution.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].
    

    UPDATE (2016/2/13):
    The return format had been changed to zero-based indices. Please read the above updated description carefully.

    思路

    第一个想法是找出在给出的数中两两组合,若和为目标则存入结果。但这样复杂度为O(n2),显然需要改进。

    改进的思路:使用哈希函数的思想。用map存储对,扫描数组,对于当前的数算出另一个数,如果map中有这个记录,则返回结果。否则把当前的数存入map,置其值为序号。

    代码

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            if (nums.size() == 0)
                return *new vector<int>(0, 0);
            map<int, size_t> hash;
            for (int i = 0; i < nums.size(); ++i) {
                int other = target - nums[i];
                if (hash[other] != 0) {
                    vector<int> result;
                    result.push_back(hash[target - nums[i]]-1);
                    result.push_back(i);
                    return result;
                }
                else
                    hash[nums[i]] = i+1;
            }
            vector<int> tmp;
            return tmp;
        }
  • 相关阅读:
    POJ 1995
    POJ 3233
    HDU 2815
    POJ 2417
    POJ 3243
    HDU 3579 线性同余方程组
    HDU 1573
    POJ 2115
    POJ 2891
    HDU 2035 不忍直视的水
  • 原文地址:https://www.cnblogs.com/yatesxu/p/5545912.html
Copyright © 2011-2022 走看看