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. seo是什么职业

    SEO(Search Engine Optimization)汉译为搜索引擎优化.seo从业者首要工作就是优化网站,使其符合搜索引擎的基本规律和满足用户的需求,进而获得大量的用户访问.SEO职业属于一 ...

  2. hdu1757 A Simple Math Problem

    Problem Description Lele now is thinking about a simple function f(x).If x < 10 f(x) = x.If x > ...

  3. 【PHP面向对象(OOP)编程入门教程】2.什么是类,什么是对象,类和对象这间的关系

    类的概念:类是具有相同属性和服务的一组对象的集合.它为属于该类的所有对象提供了统一的抽象描述,其内部包括属性和服务两个主要部分.在面向对象的编程语言中,类是一个独立的程序单位,它应该有一个类名并包括属 ...

  4. python下载网页源码 写入文本

    import urllib.request,io,os,sysreq=urllib.request.Request("http://echophp.sinaapp.com/uncategor ...

  5. C#画表格

    下面给一个简单的例子,至于多个单元格合并,请自己去实现,也就是坐标计算的事情. 至于画图,用GDI,还是DirectX画,自己选择,不过这里主要讲的是算法:坐标计算以及画的过程. 注意不要每个列都画一 ...

  6. 利用LruCache为GridView加载大量本地图片完整示例

    MainActivity如下: package cc.testlrucache; import android.os.Bundle; import android.widget.GridView; i ...

  7. HNU 12869 Sequence(循环节)

    题目链接:http://acm.hnu.cn/online/?action=problem&type=show&id=12869 解题报告:看到n的范围这么大,一看就是找规律,把前30 ...

  8. HLOI2016滚粗记

    首先,别问我HLOI是哪里....HLJ = 黑龙江... 这次的省选总结起来还是由于我太弱,考试的时候状态不好,连个线段树都没想出来 坐了好久的火车到哈尔滨,车上打了一会扑克,感觉没过多长时间就到了 ...

  9. 流畅web动画的十个法则

    from me: web动画能够带来一个非常酷炫的效果,能够让页面有一个更好的用户体验.对于良好的动画性能没有高招,除了将大量的时间放在测试和优化,当然最重要的还是要易于维护. 流畅web动画的十大法 ...

  10. job_queue_processes参数讲解

    http://blog.sina.com.cn/s/blog_62defbef0101opv0.html http://blog.163.com/donfang_jianping/blog/stati ...