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

跟以前做过的都差不多,就是要定位下标。AC代码O(nlogn)

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std; class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> copyNumbers = numbers;
vector<int> AddNum;
vector<int> Result;
sort(copyNumbers.begin(), copyNumbers.end()); //升序排序
//确定两个加数
for(int i = , j = copyNumbers.size() - ; i < j; )
{
if(copyNumbers[i] + copyNumbers[j] == target)
{
AddNum.push_back(copyNumbers[i]);
AddNum.push_back(copyNumbers[j]);
break;
}
else if(copyNumbers[i] + copyNumbers[j] < target)
{
i++;
}
else
{
j--;
}
}
//定位两个加数
for(int i = ; i < numbers.size(); i++)
{
if(numbers[i] == AddNum[] || numbers[i] == AddNum[])
{
Result.push_back(i + );
}
} return Result;
}
}; int main()
{
Solution sol;
vector<int> vec;
vec.push_back();
vec.push_back();
vec.push_back();
vec.push_back(); vector<int> ans = sol.twoSum(vec, ); return ;
}

看答案,发现有O(n)的解法。用hash表,从头到尾判断 target-当前值 在vector中是否存在O(1),因为用了hash.

O(n) runtime, O(n) space – Hash table:

We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.

public int[] twoSum(int[] numbers, int target) 
{
  Map<Integer, Integer> map = new HashMap<>();
  for (int i = ; i < numbers.length; i++) {
    int x = numbers[i];
    if (map.containsKey(target - x)) {
      return new int[] { map.get(target - x) + , i + };
    }
    map.put(x, i);
  }
  throw new IllegalArgumentException("No two sum solution");
}

【leetcode】Two Sum (easy)的更多相关文章

  1. 【LeetCode】129. Sum Root to Leaf Numbers 解题报告(Python)

    [LeetCode]129. Sum Root to Leaf Numbers 解题报告(Python) 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/pr ...

  2. 【leetcode】907. Sum of Subarray Minimums

    题目如下: 解题思路:我的想法对于数组中任意一个元素,找出其左右两边最近的小于自己的元素.例如[1,3,2,4,5,1],元素2左边比自己小的元素是1,那么大于自己的区间就是[3],右边的区间就是[4 ...

  3. 【LeetCode】633. Sum of Square Numbers

    Difficulty: Easy  More:[目录]LeetCode Java实现 Description https://leetcode.com/problems/sum-of-square-n ...

  4. 【Leetcode】404. Sum of Left Leaves

    404. Sum of Left Leaves [题目]中文版  英文版 /** * Definition for a binary tree node. * struct TreeNode { * ...

  5. 【LeetCode】Two Sum II - Input array is sorted

    [Description] Given an array of integers that is already sorted in ascending order, find two numbers ...

  6. 【leetcode】Path Sum IV

    If the depth of a tree is smaller than 5, then this tree can be represented by a list of three-digit ...

  7. 【LeetCode】404. Sum of Left Leaves 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目大意 题目大意 解题方法 递归 迭代 日期 [LeetCode] 题目地址:h ...

  8. 【LeetCode】Path Sum(路径总和)

    这道题是LeetCode里的第112道题.是我在学数据结构——二叉树的时候碰见的题.题目要求: 给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和 ...

  9. 【LeetCode】Maximize Sum Of Array After K Negations(K 次取反后最大化的数组和)

    这道题是LeetCode里的第1005道题. 题目描述: 给定一个整数数组 A,我们只能用以下方法修改该数组:我们选择某个个索引 i 并将 A[i] 替换为 -A[i],然后总共重复这个过程 K 次. ...

随机推荐

  1. c#winform选择文件,文件夹,打开指定目录方法

    private void btnFile_Click(object sender, EventArgs e) { OpenFileDialog fileDialog = new OpenFileDia ...

  2. 清北暑假模拟day2 将

    /* 爆搜,正解弃坑 */ #include<iostream> #include<cstdio> #include<string> #include<cst ...

  3. pipe-filter 真难找啊

    http://blog.csdn.net/absurd/article/details/4307903

  4. hdu.5211.Mutiple(数学推导 && 在logn的时间内求一个数的所有因子)

    Mutiple  Accepts: 476  Submissions: 1025  Time Limit: 4000/2000 MS (Java/Others)  Memory Limit: 6553 ...

  5. flexbox-CSS3弹性盒模型flexbox完整版教程

    原文链接:http://caibaojian.com/flexbox-guide.html flexbox-CSS3弹性盒模型flexbox完整版教程 A-A+ 前端博客•2014-05-08•前端开 ...

  6. .net实现微信公众账号接口开发

    说起微信公众帐号,大家都不会陌生,使用这个平台能给网站或系统增加一个新亮点,直接进入正题吧,在使用之前一定要仔细阅读官方API文档. API文档地址:http://mp.weixin.qq.com/w ...

  7. JDIC 访问Web时NullPointerException

    Exception in thread "EventThread" java.lang.NullPointerException            at org.jdeskto ...

  8. HDU 1533 最小费用最大流(模板)

    http://acm.hdu.edu.cn/showproblem.php?pid=1533 这道题直接用了模板 题意:要构建一个二分图,家对应人,连线的权值就是最短距离,求最小费用 要注意void ...

  9. HDU 1024 max sum plus

    A - Max Sum Plus Plus Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I6 ...

  10. HTTP Servlet 重要的几个方法

    HTTP Servlet继承了GencenServlet类    GencenServlet实现了两个接口··一个用于ServletConfig设置接口,一个为Servlet接口只要是(1) init ...