美文网首页
Leetcode - 两数交集&两数之和 - Python

Leetcode - 两数交集&两数之和 - Python

作者: Zpx007 | 来源:发表于2018-03-31 11:45 被阅读0次

两数交集

例如:

给定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2]

答:

class Solution(object):

    def intersect(self, nums1, nums2):

        result=[]

        dic = {}

        for num in nums1:

            if dic.has_key(num) == False:

                dic[num] = 1

            else:

                dic[num] += 1

        for num in nums2:

            if dic.has_key(num) == True and dic[num]>0:

                dic[num] -= 1

                result.append(num)

        return result

两数之和

示例

给定 nums = [2, 7, 11, 15], target = 9因为 nums[0] + nums[1] = 2 + 7 = 9所以返回 [0, 1]

class Solution(object):

    def twoSum(self, nums, target):

        arr = {}

        for i in range(len(nums)):

            if (target-nums[i]) in arr:

                return [arr[target-nums[i]],i]

            else:

                arr[nums[i]]=i

相关文章

  • Leetcode - 两数交集&两数之和 - Python

    两数交集 例如: 给定nums1=[1, 2, 2, 1],nums2=[2, 2], 返回[2, 2] 答: c...

  • Python小白 Leetcode刷题历程 No.1-No

    Python小白 Leetcode刷题历程 No.1-No.5 两数之和、两数相加、无重复字符的最长子...

  • leetcode - python - 两数之和

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被...

  • leetcode两数之和—python

    一、暴力穷举 for i,num in enumerate(nums): for j,num2 in enume...

  • Python - LeetCode - 两数之和

    描述: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返...

  • 【LeetCode通关全记录】1. 两数之和

    【LeetCode通关全记录】1. 两数之和 题目地址:1. 两数之和[https://leetcode-cn.c...

  • 两数之和-leetcode

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 你可以假设每个输入只对应一种答案,且同样的元素不能被...

  • LeetCode | 两数之和

    基础不好,笔试代码题没做好,校招没offer,赶紧来刷题 [TOC] 两数之和 这里采用两种方法来做,比较性能。 ...

  • [LeetCode] 两数之和

    给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。 nums=[2, 7, 11, 15], targe...

  • leetcode 两数之和

    给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的...

网友评论

      本文标题:Leetcode - 两数交集&两数之和 - Python

      本文链接:https://www.haomeiwen.com/subject/rcjgcftx.html