• 001-eetcode算法实现之两数之和 twoSum | python & golang实现


    # -- coding: utf-8 --

    你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

    示例:
    输入:nums = [2,7,11,15], target = 9
    输出:[0,1]
    解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1]

    """

    python

    # 蛮力枚举 时间O(n2), 空间O(1)
    def twoSum1(nums, target):
        """
        :param nums: int[]
        :param target: int
        :return: int[]
        """
        if len(nums) < 2:
            return False
    
        n = len(nums)
        for i in range(n):
            for j in range(i+1, n):
                if nums[i] + nums[j] == target:
                    return [i, j]
    
        return False
    
    # 哈希表辅助 时间O(n), 空间借助hash表,O(n)
    def twoSum(nums, target):
        """
        :param nums: int[]
        :param target: int
        :return: int[] or False
        """
        if len(nums) < 2:
            return False
    
        hashtable = dict()
        for i,num in enumerate(nums):
            if target-num in hashtable:
                return [hashtable[target - num], i]
            hashtable[num] = i
    
        return False
    
    
    if __name__ == "__main__":
    
        # 蛮力枚举测试用例
        nums1 = []
        target1 = 5
        print(twoSum1(nums1, target1)) # False
        nums2 = [1]
        print(twoSum1(nums2, target1)) # False
        nums3 = [1, 3, 5, 6]
        print(twoSum1(nums3, target1)) # False
        nums4 = [2, 5, 6, 8, 13, 3, 23]
        print(twoSum1(nums4, target1))
    
        print('*'*50)
    
        # 哈希表辅助测试用例
        nums1 = []
        target1 = 5
        print(twoSum(nums1, target1))  # False
        nums2 = [1]
        print(twoSum(nums2, target1))  # False
        nums3 = [1, 3, 5, 6]
        print(twoSum(nums3, target1)) # False
        nums4 = [2, 5, 6, 8, 13, 3, 23]
        print(twoSum(nums4, target1))
    

    golang

    package main
    
    import "fmt"
    
    func main() {
    	var nums = []int{1, 3, 4, 5, 2}
    	var target int = 5
    	res1 := twoSum1(nums, target)
    	fmt.Print(res1)
    	fmt.Println()
    	res := twoSum(nums, target)
    	fmt.Print(res)
    }
    
    // 暴力法
    func twoSum1(nums []int, target int) []int {
    	for i, num := range nums {
    		for j := i + 1; j < len(nums); j++ {
    			if num+nums[j] == target {
    				return []int{i, j}
    			}
    		}
    	}
    	return nil
    }
    
    // 哈希法
    func twoSum(nums []int, target int) []int {
    	hashtable := map[int]int{}
    	for i, x := range nums {
    		if p, ok := hashtable[target-x]; ok {
    			return []int{p, i}
    		}
    		hashtable[x] = i
    	}
    	return nil
    }
    
  • 相关阅读:
    初始Openwrt
    Angular CLI 使用教程指南参考
    Visual Studio Code怎么在同一窗口打开多个项目文件?
    mysql查看数据表是否有重复数据
    Angular UI框架 Ng-alain @delon的脚手架的生成开发模板
    VS2010 WDK7.1.0 Win7_64
    Nodejs使用TLS
    python定时执行方法
    Visual Studio Code 使用Git进行版本控制
    VSCode中设置Python解释器和pylint的波浪线问题
  • 原文地址:https://www.cnblogs.com/davis12/p/15351697.html
Copyright © 2020-2023  润新知