添加 problem 1

This commit is contained in:
YDZ
2019-03-13 03:26:05 +08:00
parent b71533eb05
commit dee614ef65
3 changed files with 148 additions and 0 deletions

View File

@@ -0,0 +1,43 @@
package leetcode
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil || l2 == nil {
return nil
}
head := &ListNode{Val: 0, Next: nil}
current := head
carry := 0
for l1 != nil || l2 != nil {
var x, y int
if l1 == nil {
x = 0
} else {
x = l1.Val
}
if l2 == nil {
y = 0
} else {
y = l2.Val
}
current.Next = &ListNode{Val: (x + y + carry) % 10, Next: nil}
current = current.Next
carry = (x + y + carry) / 10
if l1 != nil {
l1 = l1.Next
}
if l2 != nil {
l2 = l2.Next
}
}
if carry > 0 {
current.Next = &ListNode{Val: carry % 10, Next: nil}
}
return head.Next
}

View File

@@ -0,0 +1,79 @@
package leetcode
import (
"fmt"
"testing"
)
type question2 struct {
para2
ans2
}
// para 是参数
// one 代表第一个参数
type para2 struct {
one []int
another []int
}
// ans 是答案
// one 代表第一个答案
type ans2 struct {
one []int
}
func Test_Problem2(t *testing.T) {
qs := []question2{
question2{
para2{[]int{}, []int{}},
ans2{[]int{}},
},
question2{
para2{[]int{1}, []int{1}},
ans2{[]int{2}},
},
question2{
para2{[]int{1, 2, 3, 4}, []int{1, 2, 3, 4}},
ans2{[]int{2, 4, 6, 8}},
},
question2{
para2{[]int{1, 2, 3, 4, 5}, []int{1, 2, 3, 4, 5}},
ans2{[]int{2, 4, 6, 8, 0, 1}},
},
question2{
para2{[]int{1}, []int{9, 9, 9, 9, 9}},
ans2{[]int{0, 0, 0, 0, 0, 1}},
},
question2{
para2{[]int{9, 9, 9, 9, 9}, []int{1}},
ans2{[]int{0, 0, 0, 0, 0, 1}},
},
question2{
para2{[]int{2, 4, 3}, []int{5, 6, 4}},
ans2{[]int{7, 0, 8}},
},
question2{
para2{[]int{1, 8, 3}, []int{7, 1}},
ans2{[]int{8, 9, 3}},
},
// 如需多个测试,可以复制上方元素。
}
fmt.Printf("------------------------Leetcode Problem 2------------------------\n")
for _, q := range qs {
_, p := q.ans2, q.para2
fmt.Printf("【input】:%v 【output】:%v\n", p, L2s(addTwoNumbers(S2l(p.one), S2l(p.another))))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,26 @@
# [1. Two Sum](https://leetcode.com/problems/two-sum/)
## 题目
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
```
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
```
## 题目大意
在数组中找到 2 个数之和等于给定值的数字,结果返回 2 个数字在数组中的下标。
这道题最优的做法时间复杂度是 O(n)。
顺序扫描数组,对每一个元素,在 map 中找能组合给定值的另一半数字,如果找到了,直接返回 2 个数字的下标即可。如果找不到,就把这个数字存入 map 中,等待扫到“另一半”数字的时候,再取出来返回结果。