算法练习之两数之和

上周五(1.4号)看到群里有再说力扣(https://leetcode-cn.com/)的算法题,自己就去搜索了下,发现是练习算法、数据库、shell的平台,很不错。

周五下午在测试的间隙,自己做了一道简单的算法题,刚好把这两天复习的python的基础知识复习了。

算法题目:

python3代码

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        hashmap=[]
        for i  in range (0,len(nums)):
            anthor=target-nums[i]
            for j in range(i,len(nums)):
                if nums[j]==anthor and i !=j:
                    hashmap.append(i)
                    hashmap.append(j)
                    return list (hashmap)

 总结思路及知识点

1.题目要求:给定任意一列表(列表内容为数字),再给定一个目标值target,求列表中哪两个数字加起来和等于target,返回两个数字的下标(列表形式)

  思路:

(1)使用循环的方式  第一个数字与其他数字进行相加,如果不等于target,继续以第二个数字与第三个以后的数字进行相加,依次判断   。。。。

(2)使用相减的方式 

(3)循环的取值范围

(4)不能将同一个数加两次

2.知识点:

(1)for 循环(取值范围)  、  range 函数、求列表长度的函数len 

(2)空列表、列表的追加  append     

猜你喜欢

转载自www.cnblogs.com/eosclover/p/10230312.html