LeetCode — Two Sum

来源:互联网 发布:keep the windows open 编辑:程序博客网 时间:2024/04/29 06:51

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


Solution:

class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {    vector<int> result;                  vector<int> new_numbers(numbers);      sort(new_numbers.begin(), new_numbers.end());                      int head = 0;       int tail = new_numbers.size()-1;        int indexI = 0;      int indexJ = numbers.size() - 1;      while(head < tail)      {              int sum = new_numbers[head] + new_numbers[tail];          if (sum < target)          {              head++;                 }                  else if(sum > target)          {              tail--;                }                 else          {              int index1, index2;              for(int i = indexI; i < numbers.size(); i++)              {                  if(numbers[i] == new_numbers[head])                  {                        index1 = i + 1;                        indexI = i + 1;                        break;                               }                     }                            for(int j = indexJ; j >= 0; j--)              {                  if(numbers[j] == new_numbers[tail])                  {                        index2 = j + 1;                        indexJ = j - 1;                        break;                  }                     }                                     if(index1 < index2)                {                result.push_back(index1);                  result.push_back(index2);              }            else            {                result.push_back(index2);                  result.push_back(index1);             }            head++;              tail--;                     }        }      return result;                }};
0 0
原创粉丝点击