Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
思路:先將輸入的array排序,再用前後夾擊的方式,取得答案。
如果 兩數相加 < 目標,代表左邊的index要往下一個移動。
如果 兩數相加 > 目標,代表右邊的index要往前一個移動。
typedef struct Number{
int index;
int value;
}Number;
bool compare(const Number & num1,const Number & num2){
return num1.value < num2.value;
}
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target)
{
<span style="white-space:pre"> </span>// 因為排序完 index就會錯亂,先用Number記起來
vector<Number> my_nums;
Number number;
for(int index = 0; index < nums.size(); index++) {
number.value = nums[index];
number.index = index;
my_nums.push_back(number);
}
<span style="white-space:pre"> </span>//排序
sort(my_nums.begin(), my_nums.end(), compare);
vector<int> result;
int begin = 0;
int tail = my_nums.size() - 1;
<span style="white-space:pre"> </span>//開始夾擊
for (int index = 0; index < nums.size(); index++) {
if(my_nums[begin].value + my_nums[tail].value < target) {
begin++;
continue;
}
if(my_nums[begin].value + my_nums[tail].value > target) {
tail--;
continue;
}
<pre name="code" class="cpp" style="color: rgb(51, 51, 51); font-size: 14px;"> if(my_nums[begin].value + my_nums[tail].value == target) {
if (my_nums[begin].index > my_nums[tail].index) {
result.push_back(my_nums[tail].index);
result.push_back(my_nums[begin].index);
} else {
result.push_back(my_nums[begin].index);
result.push_back(my_nums[tail].index);
}
return result;
}
} return result; }};