Two Sum

朱雀 2022-09-28 05:54 207阅读 0赞

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:

  1. Given nums = [2, 7, 11, 15], target = 9,
  2. Because nums[0] + nums[1] = 2 + 7 = 9,
  3. return [0, 1].

解法:

  1. class Solution {
  2. public:
  3. vector<int> twoSum(vector<int>& nums, int target) {
  4. vector<int> vect;
  5. for(int i = 0; i < nums.size(); ++i)
  6. {
  7. for (int j = i+1; j < nums.size(); ++j)
  8. {
  9. if (nums[i] + nums[j] == target)
  10. {
  11. vect.push_back(i);
  12. vect.push_back(j);
  13. }
  14. }
  15. }
  16. return vect;
  17. }
  18. };

发表评论

表情:
评论列表 (有 0 条评论,207人围观)

还没有评论,来说两句吧...

相关阅读