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. ubuntu 14.04 安装mysql server的分支MariaDB Server初级教程

    序,MariaDB Server是Mysql的fork版本,与Mysql完美兼容,mysql在10年被sun收购,后sun被oracle收购,后mysql的创建者及项目长期技术带头人之一的Michae ...

  2. LYDSY模拟赛day9 2048

    /* 大模拟题,做的时候思路还是比较清晰的 */ #include<iostream> #include<cstdio> #include<string> #inc ...

  3. 清北暑假模拟day1 生活

    /* 数字三角形,要求第K大的值,可以推知,如果得知k的范围,那么一定是在上一行可转移状态的对应范围内(反证法可以证明),这个在背包九讲里也有提及 */ #include<cstdio> ...

  4. JS补充

    JavaScript JavaScript 使用那些老旧的实例可能会在 <script> 标签中使用 type="text/javascript".现在已经不必这样做了 ...

  5. brew gradle

    cat /usr/local/Library/Taps/homebrew/homebrew-versions/gradle221.rb GRADLE_HOME=/Users/temp/gradle22 ...

  6. C++ 模拟虚拟键盘按键表

    键盘VK键值列表 /* Virtual Keys, Standard Set*/ VK_LBUTTON                                      0x01 VK_RBU ...

  7. 几个简单实用的css效果

    1.要使按钮具有3D效果,只要将它的左上部分边框设置为浅色,右下部分边框设置为深色即可. eg:#button { background: #888; border: 2px solid; borde ...

  8. objc/runtime

    "T@\"MyInnerObject\",&,N,V_myInnerObject" MyInnerObject "Td,N,V_cgfloat ...

  9. Android学习笔记(十三)——广播机制

     //此系列博文是<第一行Android代码>的学习笔记,如有错漏,欢迎指正! Android 中的每个应用程序都可以对自己感兴趣的广播进行注册,这样该程序就只会接收到自己所关心的广播内容 ...

  10. python 字典 注意点

    dict()构造函数直接从键-值对序列创建字典: >>> >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4 ...