1. the analysis of the problem
Now we get some information from the question:
A array named nums,it includeds some intergers;
An integer named target;
What should we do:we need add two numbers from the nums to make it euqates target then return the indices(or indexs)of the two numbers;
example:Input: nums = [2,7,11,15], target = 9
Output: [0,1]
when the array nums=[2,7,11,15],we found that only 2+7=9,so we need return the indices of "2" and "7",which is 0 and 1,so the output is [0,1]
Precondition:only one solution in the array given to us,so it won't happen the situation like nums=[1,2,3,4],target=5,because the answer can be 1+4 or 2+3,so it won't happen.and we also can not use the same number for twice,
like in the example:
Input: nums = [3,3], target = 6
Output: [0,1]
we can not use the first "3" twice so we can not get the answer[0,0]
2.the method to find the two number
I guess most of us will consider about calculating all possibilities
so let us use the example of nums = [2,7,11,15], target = 9, at first we need add 2+7,then 2+11,2+15,7+11,7+15,11+15,and check the sum whether equate the target 9,once we find the equal relationship we can end the calculation cause there is only one solution exactly,
so how we can do this by codes?
we can start with the nums[0]
0 is the indice of the array,and it start from 0 in any array,it symbols the number in the position of "0+1",in the array nums it is 2
and then we add the nums[0] with nums[1],it represent 2+7,
then add the nums[0] with nums[2],it represent 2+11,then nums[0]+nums[3] ,nums[1]+nums[2],nums[1]+nums[3] ,nums[2]+nums[3]
so we can find the rules:
1.fisrt number start from nums[0] to nums[length -2].(we define the lenghth is the quantity of the numbers in the array)
2.the indice of second number is always 1 greater than first number.
so we have key codes as;
int n=nums.size();//define n as the length of array nums[]
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(nums[i]+nums[j]==target){
return {i,j};
then we add this to the given code to spell into a complete code.
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
//num is the array which we need find two elements to get the right answer.vector is the similar form of array,we can ignore the difference right now.
//first we make a integer
int n=nums.size();
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(nums[i]+nums[j]==target){
return {i,j};
}
}
}
return {};//no solution found
}
};
Top comments (0)