LeetCode OJ 第1题 Two Sum 解题报告

来源:互联网 发布:广东梅县东山中学 知乎 编辑:程序博客网 时间:2024/05/17 22:04

试题

试题链接

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

试题大意

给定一组整数,用numbers表示,给定一个整数,用target表示。
请问numbers中的第几个数与第几个数相加等于target。(1起计数)

解题思路

由于数据量不大,可以直接暴力水过。

第一步:从小到大排序,当然同时需要记录原始的下标。
所以先把数据复制到vector <pair<int,int> >中,pair::first储存原始下标,pair::second储存原始数据。然后按照来pair::second来排序。

第二步,循环枚举。
逐一枚举第一个数number1,然后第二个数必为target-number1,找到target-number1是否存在于numbers中就行了。直到存在为止。这里查找可以用二分查找,因为前面第一步已经排序排好了。

第三步,输出这两个数的原始下标

源代码

bool compare(const pair<int, int> &a, const pair <int, int> &b){    return a.second < b.second;}class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        int length = nums.size();        vector <pair<int,int> > v;        for (int i = 0; i < length; ++i)            v.push_back(make_pair<int, int>(i + 1, (int)nums[i]));        sort(v.begin(), v.end(), compare);        for (vector <pair<int,int> >::iterator itr = v.begin();            itr != v.end(); ++itr)        {            pair<int,int> diff;            diff.second = target - itr->second;            vector <pair<int,int> >::iterator itr_tmp = itr;            ++itr_tmp;            pair<vector <pair<int,int> >::iterator, vector <pair<int,int> >::iterator> p = equal_range(itr_tmp, v.end(), diff, compare);            if (p.first != p.second)            {                vector <int> ret;                if (itr->first < p.first->first)                {                    ret.push_back(itr->first);                    ret.push_back(p.first->first);                }                else                {                    ret.push_back(p.first->first);                    ret.push_back(itr->first);                }                return ret;            }        }    }};
0 0
原创粉丝点击