Problem description :
set up nums Array ,target Is an array nums The result of adding two elements in
Such as , Given target, Find the additive elements in the array , And give the subscript , Such as :
nums = [1,3,6,4,7]
target = 9
The return subscript is [2,1]( There is no order )
Read the title , Start typing code :
analysis :
Because you want to return the subscript , So we can use len(nums)-1 Get the last bit of the subscript , It can be used for i in range(len(nums)-1) Get the subscript of each element because it is the sum of two numbers , So we can still use for k in range(len(nums)-1) Get another element , Because even elements cannot be the same subscript , therefore k Scope to be used i+1 Change the starting value to for k in range(i+1,len(nums)-1)
After you get the subscript, you can use nums[I] + nums[k] == target To discuss the specific value of the subscript , Get these and you can start , First come Python edition :
'''leetcode The previous functions cannot be used directly , We assign it manually nums For example :'''
def solution(i,j):
nums = [1,4,7,8,2,4,3]
target = 7
for i in range(len(nums)-1):
for n in range(i+1,len(nums)-1):
if nums[i] + nums[n] == 9:
return i,n
solution()
We'll take C Language version , The theory is unchanging , Just change the grammar a little :
#include <stdio.h>
int main()
{
int target,i,n,lenth;
int nums[] = {
1,4,6,2,9};
lenth = sizeof(nums)/sizeof(int);//C The method of calculating length in language
target = 7;
for(i = 0;i<lenth;i++)
{
for(n = i+1;i<lenth;n++)
{
if (nums[n] + nums[i] == target)
{
printf("%d,%d",i,n);
// return i,n; I don't know why , use return There is no return value
}
}
}
}
The above procedures are feasible , But the time complexity needs to be optimized .
————————————END———————————————