1 Star 0 Fork 0

libow-python / python_leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
tosum.py 868 Bytes
一键复制 编辑 原始数据 按行查看 历史
libow-python 提交于 2021-12-24 18:00 . leetcode
def twoSum(nums, target):
"""两数之和 ----- 哈希"""
# res_dict = {}
# res_lst = []
# for index, num in enumerate(nums):
# res = target - num
# if res_dict.get(res) is not None:
# res_lst.append(res_dict[res])
# res_lst.append(index)
# else:
# res_dict[num] = index
# return res_lst
"""两数之和,指针法"""
left = 0
right = len(nums) - 1
lst = []
while left <= right:
print(left,right)
if nums[left] + nums[right] - target < 0:
left += 1
elif nums[left] + nums[right] - target > 0:
right -= 1
else:
lst.append(left)
lst.append(right)
left += 1
return lst
if __name__ == '__main__':
nums = [2, 7, 11 ,15]
target = 14
print(twoSum(nums, target))
1
https://gitee.com/libow-python/python_leetcode.git
git@gitee.com:libow-python/python_leetcode.git
libow-python
python_leetcode
python_leetcode
master

搜索帮助