演算法——Week 1
阿新 • • 發佈:2018-12-21
1.Two Sum
問題描述
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, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
解題思路
本題是在陣列中找到兩個和為目標值的數,並返回其索引。首先從陣列位置i開始,從0之後開始查詢目標值target - array[i]是否存在,若存在,則記錄下當前兩個數的位置i和j, 由於array[i] + array[j] = target,即可得到解。
程式碼如下
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
int size = nums.size();
int * array = new int[size];
for(int i = 0; i < size; i++)
array[i] = nums.at(i);
for (int i = 0; i < size; i++) {
int key = target - array[i];
int j = 0;
for(j = i + 1; j < size; j++) {
if(array[j] == key) {
break ;
}
}
if (j != size) {
result.push_back(i);
result.push_back(j);
break;
}
}
return result;
}
};