首页 > 其他 > 详细

leetcode-两数之和

时间:2020-01-16 20:47:56      阅读:55      评论:0      收藏:0      [点我收藏+]

leetcode-两数之和

题目内容如下:
给定一个整数数组 nums?和一个目标值 target,请你在该数组中找出和为目标值的那?两个?整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
    给定 nums = [2, 7, 11, 15], target = 9
    因为 nums[0] + nums[1] = 2 + 7 = 9
    所以返回 [0, 1]
首先,基本思路遍历数组每个元素,在遍历中得到差值再从数组中遍历搜索该差值。
class Solution:
    def twoSum(self, nums: list, target: int) -> list:
        for i in range(len(nums)):
            find_num = target - nums[i]
                for j in range(len(nums)):
                    if  find_num == nums[j] and j != i:
                        return [i, j]


 if __name__ == "__main__":
    print(Solution().twoSum([2, 7, 11, 15], 9))
上面思路应该改进:得到了差值就变成了查找元素问题了,故使用二分法进行查找,故先对数组进行排序。但是答案要求拿到数组元素下标,显然排序过的数组下标已打乱,故我们再拿着找到的元素再去原数组找到下标,返回答案,代码如下:
  class Solution:
      def  twoSum(self, nums: list, target: int) -> list:
        arr = sorted(nums)
        for i in range(len(arr)):
            key = target - nums[i] 
            find_num = self.binary_search(arr, key)
            if find_num != None:  
                j = 0
                find = True
                while j < len(nums):   
                    if j == i:
                        j += 1                     
                    if nums[j] != find_num:
                        if j == len(nums) - 1:
                            find = False
                            break
                        j += 1               
                    else:
                        break
                if find:
                    return [i, j]
                
    def binary_search(self, nums: list, key: int) -> int:
        start = 0
        end = len(nums) - 1
        while start <= end:
            index = (start + end) // 2
            if nums[index] == key:
                return nums[index]
            elif nums[index] > key:
                end = index - 1
            else:
                start = index + 1
        return None

leetcode-两数之和

原文:https://www.cnblogs.com/blogfyang/p/12203036.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!