程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[leetcode] punch in 𞓜 two element addition problem implemented by Python and C

編輯:Python

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———————————————


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved