LeetCode--Go and Python3解两数之和

两数之和

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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

Go

遍历数组

可以通过双for循环来首先两数之和

func twoSum(nums []int, target int) []int {
	len := len(nums)
	result := []int{}
    for i:=0; i<len-1; i++{
        for j:=i+1; j<len; j++{
			if nums[i]+nums[j] == target{
				result = append(result, i, j)
				return result
			}
		}
	}
	return result
}

一遍hash表

一遍哈希表。
在进行迭代并将元素插入到表中的同时,我们还会回过头来检查表中是否已经存在可以和当前元素相加得到与target相同的目标元素。如果它存在,那我们已经找到了对应解,并立即将其返回。
步骤

  1. 构造一个空表 hash = {} // 类似python里的字典
  2. 按顺序遍历数组
  3. 每次通过target-当前元素计算出目标元素的值
  4. 如果目标元素存在hash表内,说明已经找到,则返回当前元素和目标元素的对应下标即可。
  5. 若不在表内则需要更新hash表–> hash[当前元素]=地址, 并回到步骤2
  6. 直到遍历结束,返回None
func twoSum_hash(nums []int, target int) []int {
	tables := make(map[int]int) // 声明一个空字典

	for index, value := range nums {
		// index为地址,value为nums[index]的值
		tmp := target - value
		fmt.Printf("index %d\tvalue %d\ttmp %d\n",index, value, tmp)
		i, ok := tables[tmp]
		fmt.Printf("tmp %d\ti %d\tok %v\n", tmp,i,ok)
		if i, ok := tables[tmp]; ok {
			return []int{i, index}
		}
		tables[value] = index
	}
	return []int{}
}

Python3

遍历数组

def twoSum(self, nums, target):
    for i in range(len(nums)-1):
        for j in range(i+1,len(nums)):
            if nums[i] + nums[j] == target:
                return [i,j]

    return None

一遍hash表

def twoSum(self, nums, target):
	tables = {}
	for index, num in enumerate(nums):
	    present_num = target - num
	    # present_num用于存储目标元素的值
	    if present_num in tables:
	        return [tables[present_num], index]
	   	tables[num] = index
	return None

遍历数组和一遍hash表的对比

遍历数组的时间复杂度: O(n^2)
一遍hash表的时间复杂度: O(n)

坚持两天一题!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章