1Two Sum

来源:互联网 发布:淘宝前100名免单怎么看 编辑:程序博客网 时间:2024/06/05 08:25

Leetcode 1:

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

将数组从小到大排序,假设为0,1,2,3,4,5,6,7,8,9

令index1 = 0, index2 = 9 则计算index1 和index2 对应值的和sum ,如果sun < target, 则index1  加 1 ,否则 index2 减 1. 直到等于target

class Solution {public:static bool my_cmp(pair<int, int> a, pair<int, int> b){return a.first < b.first;}vector<int> twoSum(vector<int> &numbers, int target) {int index1 = 0, index2 = numbers.size();vector<pair<int, int>> my_numbers;for (int i = 0; i < index2; i++){my_numbers.push_back(make_pair(numbers[i], i + 1));}sort(my_numbers.begin(),my_numbers.end(),my_cmp);index2--;while (index1 < index2){int sum = my_numbers[index1].first + my_numbers[index2].first;if (sum < target){index1++;}else if (sum > target) {index2--;}else if (sum == target){vector<int> my_return;if (my_numbers[index1].second < my_numbers[index2].second){my_return.push_back(my_numbers[index1].second);my_return.push_back(my_numbers[index2].second);}else{my_return.push_back(my_numbers[index2].second);my_return.push_back(my_numbers[index1].second);}return my_return;}}}};



0 0
原创粉丝点击