leetcode Two Sum

来源:互联网 发布:淘宝返利的网站有哪些 编辑:程序博客网 时间:2024/05/01 22:38

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


思路用multimap来存储numbers与下标,在查找的时候分两种情况,根据target == 2 * numbers[i]判断,如果是,需要找出第一个位置,并判断后一个位置的值是否等于numbers[i],第二种直接查找target-numbers[i],然后做判断即可。

vector<int> twoSum(vector<int> &numbers, int target) {        multimap<int, int> maps;        multimap<int, int>::iterator it;        vector<int> vec;        bool check;        for(int i = 0; i < numbers.size(); i++){            check = false;            maps.insert(make_pair(numbers[i], i));            it = maps.lower_bound(target - numbers[i]);            if(target == 2 * numbers[i]){                it++;                check = true;            }            if(it != maps.end()  && it -> first == target - numbers[i]){                if(check)                    it--;                vec.push_back(it->second +1);                vec.push_back(i+1);                break;            }        }        return vec;    }


0 0