LeetCode-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,
return [0, 1].
本题给出一个数组与一个目标值,要求找到数组中和为目标值的两个数,并返回其二者所在数组中的索引。
作为LeetCode算法题库中的第一题,本题属于较为基础的题目,当然,再简单的题目也存在优化算法,不过本次提供的是一种最为基础的算法。如冒泡排序般采用两个循环,将数组中的值两两相加,找到答案后返回即可。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> re;
for (int i = 0; i < nums.size()-1; i++) {
for (int j = i+1; j < nums.size(); j++) {
if (nums[i]+nums[j] == target) {
re.push_back(i);
re.push_back(j);
return re;
}
}
}
}
};
整个算法难度不大,并且由于一开始就给出了数组中必有相加的和等于目标值的两个数的限制条件,所以也不存在边界问题。