【第22期】观点:IT 行业加班,到底有没有价值?

Two sum

原创 2015年11月17日 17:10:43

题意:
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
代码:

class Solution {
private:
    map<int,int> mp;
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        // 注意return的序号从1开始
        // 想法比较巧妙:主要思想映射
        int index1=-1,index2=-1;
        for(int i=0;i<nums.size();++i){
            if(mp.find(nums[i])==mp.end()){
                mp.insert(make_pair(target-nums[i],nums[i]));
            }
            else{
                if(mp.find(nums[i])->second==target-nums[i]){
                     index2=i;
                     break;
                }
                else mp.insert(make_pair(target-nums[i],nums[i]));
            }
        }
        for(int i=0;i<nums.size();++i){
            if(nums[index2]+nums[i]==target){
                index1=i;
                break;
             }
        }
        return {index1+1,index2+1};
    }
};
版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

【小熊刷题】Two Sum II - sorted array

Two SumQuestion:Similar to Question [1. Two Sum], except that the input array is already sorted in a...

Sum of Two Linked Lists - 2

Given two numbers represented by two linked lists, write a function that returns sum list. The sum list is linked list r

程序员升职加薪指南!还缺一个“证”!

CSDN出品,立即查看!

29. Divide Two Integers/49. Group Anagrams/96. Unique Binary Search Trees/560. Subarray Sum Equals K

Divide Two Integers Problem Description Implementation29. Divide Two IntegersProblem DescriptionDivi...

Which Numbers are the Sum of Two Squares?

The main goal of today's lecture is to prove the following theorem. Theorem 1.1 A number

Two Sum类问题

引言:Two Sum类问题属于对撞型双指针问题,这类问题的思路不难,但是变形以及问法比较多,这里将部分题目做归纳总结。 在Two Sum问题中,需要用的预处理为排序。但有的时候需要返回索引的位置,就...
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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