- 1.题解
- 方法:暴力
- 2.力扣C++源码
- 3.VS可运行源程序
很简单,双层for循环遍历
2.力扣C++源码class Solution { public: vector3.VS可运行源程序twoSum(vector & nums, int target) { vector res; for (int i = 0; i < nums.size(); i++) { for (int j = i + 1; j < nums.size(); j++) { int sum = nums[i] + nums[j]; if (sum == target) { res.push_back(i); res.push_back(j); break; } } } return res; } };
#include#include #include #include #include #include #include #include #include #pragma warning(disable:4996) using namespace std; class Solution { public: vector twoSum(vector & nums, int target) { vector res; for (int i = 0; i < nums.size(); i++) { for (int j = i + 1; j < nums.size(); j++) { int sum = nums[i] + nums[j]; if (sum == target) { res.push_back(i); res.push_back(j); break; } } } return res; } }; int main() { printf("输入数组大小:"); int n; scanf("%d", &n); printf("输入数组元素:"); int num; vector nums; for (int i = 0; i < n; i++) { scanf("%d", &num); nums.push_back(num); } printf("输入目标值:"); int target; scanf("%d", &target); Solution test; vector res = test.twoSum(nums, target); printf("符合条件的两个整数的下标分别为:%d %d", res[0], res[1]); printf("n"); system("pause"); return 0; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)