Leetcode gives a number A and a vector B, finding out that the 2 numbers in the vector b are added equal to a, and the position of the two numbers in the vector is output

Source: Internet
Author: User

See C++primer Plus look bored, the first time do Leetcode practice, originally want to do two-dimensional vector, results always pass, check the reason, must use one-dimensional ...

One-dimensional answers:

Class Solution {
Public
Vector<int> twosum (vector<int>& nums, int target)
{
int cout = Nums.size (); Get the size of the vector
vector<int>ret; Defining vectors
for (int i = 0; i<cout; i++)
{
for (int j = i + 1; j<cout; J + +)
{
if ((Nums[i] + nums[j]) = = target)
{
Ret.push_back (i); Get the location of the target value
Ret.push_back (j);
}
}
}
return ret;
}
};

Two-dimensional answer:

Class Solution {

Public:vector<vector<int>> twosum (vector<int>& nums, int target)

{int cout = Nums.size (); Get the size of a two-dimensional vector

Vector<vector<int>>ret (cout); Defining two-dimensional vectors

for (int i = 0; I <cout; i++)

Ret[i].resize (2); Initialize two-dimensional vectors

int i0 = 0;

for (int i = 0; i<cout; i++)

{for (int j = i + 1; j<cout; J + +)

{if ((Nums[i] + nums[j]) = = target)

{Ret[i0][0] = i; Get the location of the target value

Ret[i0][1] = j;

i0++;

}

}

}

Ret.resize (I0 + 1); Keep only the useful parts

for (int i = 0; i < I0; i++)

std:: cout << ret[i][0] << "," << ret[i][1] << Std::endl;

return ret;

}

};

Leetcode gives a number A and a vector B, finding out that the 2 numbers in the vector b are added equal to a, and the position of the two numbers in the vector is output

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.