leetcode1

原创 2016年06月02日 11:01:57

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.


代码:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> ret(2,-1);
        unordered_map<int, int> m;    //value->index map
        for(int i = 0; i < nums.size(); i ++)
        {
            if(m.find(target-nums[i])== m.end())  //target-numbers[i] appeared 
                m[nums[i]]=i;
            else
           {
                ret[0] = m[target-nums[i]]; 
                ret[1] = i;
            }
        }
    return ret;
    }
    
};










【LeetCode-1】 Two Sum(C++)

Given an array of integers, return indices of the two numbers such that they add up to a specific ta...
  • liujiayu1015
  • liujiayu1015
  • 2016-05-24 18:43:49
  • 190

Leetcode1.Two Sum

又回来刷题了,小一个月被各种事情耽误没有写代码,再写的时候完全手生。 接下来的时间要全身心准备年后的各种内推,希望3月能去一个好公司实习。 无他,唯手熟尔。 这题还是挺简单的,我第一反应就是用双...
  • Barbie_1229
  • Barbie_1229
  • 2018-01-25 15:04:29
  • 20

LeetCode1 TwoSum (java实现)

原题: Given an array of integers, return indices of the two numbers such that they add up to a spec...
  • fyy607
  • fyy607
  • 2016-12-28 11:04:16
  • 111

python leetcode1

Given an array of integers, return indices of the two numbers such that they add up to a specific ta...
  • weiweimueng
  • weiweimueng
  • 2017-08-25 20:14:36
  • 91

Leetcode1

Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].clas...
  • m0_37639542
  • m0_37639542
  • 2017-10-28 22:19:14
  • 52

LeetCode 191. Number of 1 Bits(比特数)

原题网址:https://leetcode.com/problems/number-of-1-bits/ Write a function that takes an unsigned in...
  • jmspan
  • jmspan
  • 2016-05-04 03:05:52
  • 310

LeetCode解题报告 1. Two Sum[easy]

前言 之前听说过很多次LeetCode在面试中的大量应用,通过本次算法课可以开始题目的练习觉得还是很不错的。 题目描述1. Two Sum[easy] Given an array of intege...
  • conniemessi
  • conniemessi
  • 2016-09-03 16:48:08
  • 234

LeetCode 1. Two Sum(c语言实现)

问题描述: 给定一个数组,找出两个元素,其相加等于一个给定的目标值,返回这两个元素的索引值。 Given an array of integers, return indices of the t...
  • caotuo_csdn
  • caotuo_csdn
  • 2017-12-24 22:21:56
  • 88

LeetCode 1 : Two Sum ---- 哈希&数组

原题链接:https://leetcode.com/problems/two-sum/ 一:原题内容 Given an array of integers, return indices of...
  • LaoJiu_
  • LaoJiu_
  • 2016-05-16 14:21:04
  • 682

LeetCode-1-Two Sum(C语言实现)

/**  * Note: The returned array must be malloced, assume caller calls free().  */ int* twoSum(int...
  • AI_lalaland
  • AI_lalaland
  • 2017-12-18 02:25:09
  • 49
收藏助手
不良信息举报
您举报文章:leetcode1
举报原因:
原因补充:

(最多只允许输入30个字)