zoukankan      html  css  js  c++  java
  • Leetcode 1.两数之和

    一、Leetcode之两数之和

    三种解法,其他实现可以参考leetcode解答

    1.暴力法 2.二分法 3. 哈希

    给定num,在对应数组中找到对应的两个数。

    class Solution:    
        def twoSum1(self, nums: List[int], target: int) -> List[int]:
            length = len(nums)
            for i in range(length):
                for j in range(i+1, length):
                    if nums[i] + nums[j] == target:
                        return [i, j]
    
    
        def twoSum2(self, nums: List[int], target: int) -> List[int]:
            length = len(nums)
            num_2_idx = {}     # num_2_idx = {num:idx for idx, num in enumerate(nums)} # dict会覆盖
            for i in range(length):
                if not num_2_idx.__contains__(nums[i]):
                    num_2_idx[nums[i]] = i
            ori_nums = nums
            nums = sorted(nums)  # 原有的索引已经改变了
            for i in range(length):
                left = i + 1
                right = length - 1
                complement = target - nums[i]
                while left <= right:
                    j = (left + right) // 2  # mid  
                    if nums[j] > complement:
                        right = j - 1
                    elif nums[j] < complement:  
                        left = j + 1      
                    elif nums[j] == complement:
                        i_idx = num_2_idx[nums[i]]  
                        j_idx = num_2_idx[nums[j]]             
                        if nums[i] == nums[j]:                    
                            j_idx = i_idx + 1 + ori_nums[i_idx+1:].index(nums[j])
                        return [i_idx, j_idx] # 返回的是排序前元素的索引 
    
    
        def twoSum3(self, nums: List[int], target: int) -> List[int]:  
            num_2_idx = {} # 相当于逆序的暴力法
            for i in range(len(nums)):
                complement = target - nums[i]
                if num_2_idx.__contains__(complement): 
                    return [num_2_idx.get(complement), i]                     
                num_2_idx[nums[i]] = i
    
    
        def twoSum(self, nums: List[int], target: int) -> List[int]:
            return self.twoSum2(nums, target)
  • 相关阅读:
    svn cleanup failed–previous operation has not finished 解决方法
    开源SNS社区系统推荐
    从网络获取图片本地保存
    MS SQL Server 数据库连接字符串
    KeepAlive
    Configure Git in debian
    sqlserver query time
    RPi Text to Speech (Speech Synthesis)
    SQL Joins with C# LINQ
    search or reseed identity columns in sqlserver 2008
  • 原文地址:https://www.cnblogs.com/justLittleStar/p/13722020.html
Copyright © 2011-2022 走看看