leetcode 1 two sum

Question: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 {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
    }

本题比较简单,用hashmap即可,讲一下容易出错的地方:

trap: 给的序列可能是重复的,所以我选择用两个map

//
//  main.cpp
//  leetcode
//
//  Created by YangKi on 15/11/11.
//  Copyright © 2015年 YangKi. All rights reserved.
//

#include<cstdlib>
#include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> map;
        unordered_map<int, int> map2;
        vector<int>ans;
        int size=nums.size();
        for(int i=0; i<size; i++)
        {
            if(map.find(nums[i]) == map.end())
            {
                map[ nums[i] ]= (i+1);
            }
            else//duplicate
            {
                map2[ nums[i] ]=(i+1);
            }
        }
        
        for(int i=0; i<size; i++)
        {
            if( map.find(target-nums[i]) != map.end() )//success
            {
                if(nums[i] == target-nums[i])
                {
                    if(map2.find(nums[i]) != map2.end() )
                    {
                        ans.push_back(min(map[nums[i]], map2[nums[i]]));
                        ans.push_back(max(map[nums[i]], map2[nums[i]]));
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }
                else
                {
                    ans.push_back(min(map[nums[i]], map[target-nums[i]]));
                    ans.push_back(max(map[nums[i]], map[target-nums[i]]));
                }
                break;
            }
        }
        
        return ans;
    }
};

int main()
{
    Solution *s=new Solution();
    vector<int>v={2,7,11,15};
    vector<int>vv=s->twoSum(v, 9);
    printf("%d %d\n", vv[0], vv[1]);
    return 0;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容