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

import java.util.Arrays; import java.util.HashMap; /** * @author: UniqueZ_ * @file: the first ques...

LeetCode - 380. Insert Delete GetRandom O(1)-思路详解

设计一个数据结构,该数据可以在O(1)时间内完成以下操作: 1,insert(val):插入一个元素到集合中,如果元素之前不存在。 2,remove(val):如果val在集合中存在,则删除 3,ge...

LeetCode题解:number-of-1-bits

在云南出差的时候我开始刷LeetCode上的 算法题了,一共一百八十多道题,不知道 我得做到什么时候。好了闲话不多说,先 来对我做出的第一道题写个报告: 题目链接: 点击打开链接number...

[LeetCode]1. Two Sum

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

第六周作业1(LeetCode13)

1. 题目描述Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range ...

【LeetCode编程学习(C语言)】1.Two Sum

LeetCode编程之简单篇,两个数求和,采用穷举和hash对比

LeetCode 1 - Two Sum

问题简述 Two Sum Given an array of integers, return indices of the two numbers such that th...

leetcode_1_Two Sum

最近开始刷leetcode, 这是第一题,没什么复杂的直接上代码好了 题目是:Given an array of integers, return indices of the two number...

LeetCode(1)--TwoSum

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

LeetCode-Number of 1 Bits

Question Write a function that takes an unsigned integer and returns the number of ’1’ bits it has...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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