查找和为某值的两个数

来源:互联网 发布:中国原创服装品牌 知乎 编辑:程序博客网 时间:2024/04/29 01: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


class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        vector<int> temp(numbers);        sort(temp.begin(), temp.end());        vector<int> result;        int value1;        int value2;        int left = 0;        int right = temp.size() - 1;        bool found = false;        while (left < right)        {            int sum = temp[left] + temp[right];            if (sum == target)            {                found = true;                value1 = temp[left];;                value2 = temp[right];                break;            }            else if (sum > target)            {                right--;            }            else            {                left++;            }        }            if (found)        {            int pos1 = -1;            int pos2 = -1;            int size = numbers.size();            for (int i = 0; i < size; i++)            {                if (numbers[i] == value1)                {                    pos1 = i+1;                    break;                }            }            for (int i = size-1; i >= 0; i--)            {                if (numbers[i] == value2)                {                    pos2 = i+1;                    break;                }            }                        result.push_back(pos1);            if (pos2 > pos1)            {                result.push_back(pos2);            }            else            {                result.insert(result.begin(), pos2);            }        }        return result;    }};


0 0
原创粉丝点击