Two Sum
算法老师推荐leetcode网站后,去做了第一题来感受一下难度。
题目详情:
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].
解题方法:
这道题难度程度为easy,做起来没费力气,主要是用来练练手,找回大一时学C++,和C时的感觉,以及练练最近刚学的python。
我的解决方法是最容易想到的方法:二重循环, 使数组中的数两两相加,判断是否等于target,一旦等于则退出循环,返回两个数在原数组中的下标
题目详细代码:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> temp;
bool stop = false;
for (int i = 0; i < nums.size(); i++) {
for (int j = 0; j < nums.size(); j++) {
if (nums[i] + nums[j] == target && i != j) {
temp.push_back(i);
temp.push_back(j);
stop = true;
}
if (stop) break;
}
if (stop) break;
}
return temp;
}
};
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> temp;
bool stop = false;
for (int i = 0; i < nums.size(); i++) {
for (int j = 0; j < nums.size(); j++) {
if (nums[i] + nums[j] == target && i != j) {
temp.push_back(i);
temp.push_back(j);
stop = true;
}
if (stop) break;
}
if (stop) break;
}
return temp;
}
};