Go 强悍的性能

我用 leetcode 第一题 的测试数据,测试了同一解法的 Python 实现和 Go 实现。数据可以在这里找打 leetcode01 test data · GitHub

> time python3 01-two-sum.py
#[8010, 8011]
# python3 01-two-sum.py  0.09s user 0.04s system 71% cpu 0.187 total

> go build main.go 01-two-sum.go
> time ./main               
# [8011 8010]
# ./main  0.01s user 0.01s system 72% cpu 0.017 total

下面是我的源代码(数据并不是上面提到的测试数据)

01-two-sum.py

nums = [3,2,4]
target = 6

class Solution:
    def twoSum(self, nums: 'List[int]', target: 'int') -> 'List[int]':
        hashmap = {k: v for v, k in enumerate(nums)}
        for index_a, item_a in enumerate(nums):
            item_b_wish = target - item_a
            # 目标数在词典里并且索引值不同则返回
            if (item_b_wish in hashmap) and (hashmap[item_b_wish] != index_a):
                if hashmap[item_b_wish] > index_a:
                    return [index_a, hashmap[item_b_wish]]
                else:
                    return [hashmap[item_b_wish], index_a]

op = Solution().twoSum(nums, target)
print(op)

01-two-sum.go

package main

func twoSum(nums []int, target int) []int {
    var res = []int{}
    hashmap := map[int]int{}
    for i, x := range nums {
        hashmap[x] = i
    }
    for indexA, itemA := range nums {
        itemBTarget := target - itemA
        if hashmap[itemBTarget] != indexA {
            if hashmap[itemBTarget] != 0 {
                res = []int{indexA, hashmap[itemBTarget]}
            }
        }
    }
    return res
}

main.go

package main

import "fmt"

func main() {
    var nums = []int{}

    var target = 
    var a = twoSum(nums, target)
    fmt.Println(a)
}
Comments
Write a Comment