共计 1234 个字符,预计需要花费 4 分钟才能阅读完成。
java 程序猿转 go 语言,通过 leetcode 刷题来相熟 go 语言,实现语言根底和语法根底的相熟
1. 两数之和
暴力破解:
func twoSum(nums []int, target int) []int {for i := 0; i < len(nums) - 1; i++ {for j := i + 1; j < len(nums); j++ {if (nums[j] + nums[i] == target) {return []int {i, j};
}
}
}
return nil
}
哈希表:
func twoSum(nums []int, target int) []int {hashmap := make(map[int] int)
for index, value := range nums {if v, ok := hashmap[value]; ok {return []int{index, v}
}
hashmap[target - value] = index
}
return nil
}
2. 两数相加
递归版本(链表或者树的问题都要尽量想一个递归的)
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {return addTwoNumbersHelp(l1, l2, 0);
}
func addTwoNumbersHelp(l1 *ListNode, l2 *ListNode, add int) *ListNode {
if l1 == nil && l2 == nil && add == 0 {return nil}
if (l1 != nil) {
add = l1.Val + add;
l1 = l1.Next
}
if (l2 != nil) {
add = l2.Val + add;
l2 = l2.Next
}
node := ListNode{
add % 10,
addTwoNumbersHelp(l1, l2, add / 10),
}
return &node;
}
非递归版本
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {head := ListNode{};
tail := &head;
add := 0;
for l1 != nil && l2 != nil {
add += l1.Val + l2.Val;
l1 = l1.Next;
l2 = l2.Next;
cur := ListNode{
Val: add % 10,
Next: nil,
}
tail.Next = &cur;
tail = &cur;
add = add / 10;
}
for l1 != nil {
add += l1.Val;
l1 = l1.Next;
cur := ListNode{
Val: add % 10,
Next: nil,
}
tail.Next = &cur;
tail = &cur;
add = add / 10;
}
for l2 != nil {
add += l2.Val;
l2 = l2.Next;
cur := ListNode{
Val: add % 10,
Next: nil,
}
tail.Next = &cur;
tail = &cur;
add = add / 10;
}
if add != 0 {tail.Next = &ListNode{1,nil}
}
return head.Next;
}
正文完