other

package
v0.0.0-...-10bc058 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 12, 2021 License: Apache-2.0 Imports: 4 Imported by: 0

README

two sum

1. 问题描述

  • 给定一数组如[2,7,11,15]和一目标值9,求数组中两个元素为之和为目标值,这两个元素的下标。

2. 解题思路

  • 暴力法。两层循环,第一层循环遍历数组取数m,第二遍循环遍历剩下的数组取数n,如果n = traget - m则返回下标即可。
  • map法。定义一个以数组元素为key、下标为value的map,遍历数组取数m,查询map中是否有traget - m为key的元素,如果有,返回下边,如果没有,则将数m作为key,下标作为value存入map,继续遍历。

3. 性能测试

map法为TwoSum1,暴力法为TwoSum2,详见two_sum.go

  • 当数组中元素为1W时,benchmark测试结果对比:
➜  1.two_sum git:(feat/golang) ✗ go test -bench .
goos: darwin
goarch: amd64
pkg: github.com/driverfun/leetcode-in-multi-language/golang/1.two_sum
BenchmarkTwoSumV1-12                3000            443212 ns/op
BenchmarkTwoSumV2-12                  50          25868747 ns/op
PASS
ok      github.com/driverfun/leetcode-in-multi-language/golang/1.two_sum        2.721s

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ArrayPairSumV2

func ArrayPairSumV2(nums []int) int

func Exist

func Exist(board [][]byte, word string) bool

func FindDisappearedNumbers

func FindDisappearedNumbers(nums []int) []int

func FindMedianSortedArrays

func FindMedianSortedArrays(nums1 []int, nums2 []int) float64

func GetKthElement

func GetKthElement(nums1, nums2 []int, k int) int

func LongestConsecutiveV2

func LongestConsecutiveV2(nums []int) int

func MergeV2

func MergeV2(nums1 []int, m int, nums2 []int, n int)

合并两个有序数组,原地合并 先把 nums1 的部分 copy 到后边,然后再跟 nums2 比较

func MinSwapsCouplesV1

func MinSwapsCouplesV1(row []int) int

利用map,时间复杂度 O(n)

func MinSwapsCouplesV2

func MinSwapsCouplesV2(row []int) int

相比于 v1, 用一个数组表示原 row 的 value 的索引关系。 因为 row 是序列 0...len(row)-1 的一个全排列,所以可以考虑用一个数组表示

func MinSwapsCouplesV3

func MinSwapsCouplesV3(row []int) int

广度优先搜索

func MinSwapsCouplesV4

func MinSwapsCouplesV4(row []int) int

func MyAtoi

func MyAtoi(str string) int

func NewUnionFindV2

func NewUnionFindV2(n int) *unionFindV2

func NextPermutation

func NextPermutation(nums []int)

func ReverseWords

func ReverseWords(s string) string

func TwoSumV1

func TwoSumV1(nums []int, target int) []int

use map. O(n)

func TwoSumV2

func TwoSumV2(nums []int, target int) []int

scan in circle violently

Types

type Heap

type Heap []int // 定义一个类型

func (Heap) Len

func (h Heap) Len() int

绑定len方法,返回长度

func (Heap) Less

func (h Heap) Less(i, j int) bool

绑定less方法

func (*Heap) Pop

func (h *Heap) Pop() (v interface{})

绑定pop方法,从最后拿出一个元素并返回

func (*Heap) Push

func (h *Heap) Push(x interface{})

绑定push方法,插入新元素

func (Heap) Swap

func (h Heap) Swap(i, j int)

绑定swap方法,交换两个元素位置

type ListNode

type ListNode struct {
	Val  int
	Next *ListNode
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL