LeetCode 1. Two Sum
Problem
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].
题目大意:
给定一个整数数组,返回两个数字的索引,使它们相加得到一个特定的目标。您可能假设每个输入都只有一个解决方案,并且可能不会两次使用相同的元素。
C++ Accepted代码:
简单的双循环暴力
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for(int i = 0; i < nums.size(); i++){
for(int j = i + 1; j < nums.size(); j++){
if(nums[j] == target - nums[i]){
return vector<int> {i,j};
}
}
}
}
};