力扣 题目1- 两数之和
题目
题解
n2:双重循环遍历
代码
1 #include<iostream> 2 #include<vector> 3 #include<algorithm> 4 using namespace std; 5 class Solution { 6 public: 7 vector<int> twoSum(vector<int>& nums, int target) { 8 vector<int> result = { 0,0 }; 9 for (int i = 0; i < nums.size(); i++) { 10 result[0] = i; 11 for (int j = i + 1; j < nums.size(); j++) { 12 if (nums[result[0]] + nums[j] == target) { 13 result[1] = j; 14 return result; 15 } 16 } 17 } 18 return result; 19 } 20 }; 21 22 int main() { 23 Solution sol; 24 vector<int> nums = { 3,3 }; 25 int target = 6; 26 vector<int> result=sol.twoSum(nums, target); 27 for (int i = 0; i < result.size();i++) { 28 cout << result[i]<<" "; 29 } 30 31 }