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:

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

C++代码如下

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

猜你喜欢

转载自www.cnblogs.com/LuckCoder/p/10252498.html