Skip to content

Commit 0e68d09

Browse files
authoredMar 21, 2019
Merge pull request doocs#158 from lightfish-zhang/master
add golang solution for 0002, 0003
2 parents 567c19d + fc91870 commit 0e68d09

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
 
+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* type ListNode struct {
4+
* Val int
5+
* Next *ListNode
6+
* }
7+
*
8+
* Report by leetcode.com
9+
* Runtime: 12 ms, Memory Usage: 5 MB
10+
*/
11+
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
12+
head := &ListNode{}
13+
currentNode1 := l1
14+
currentNode2 := l2
15+
currentHead := head
16+
sum := 0
17+
nextSum := 0
18+
19+
for true {
20+
if currentNode1 != nil || currentNode2 != nil {
21+
if currentNode1 == nil {
22+
sum = nextSum + currentNode2.Val
23+
nextSum = sum / 10
24+
currentNode2 = currentNode2.Next
25+
} else if currentNode2 == nil {
26+
sum = nextSum + currentNode1.Val
27+
nextSum = sum / 10
28+
currentNode1 = currentNode1.Next
29+
} else {
30+
sum = nextSum + currentNode1.Val + currentNode2.Val
31+
nextSum = sum / 10
32+
currentNode1 = currentNode1.Next
33+
currentNode2 = currentNode2.Next
34+
}
35+
currentHead.Val = sum % 10
36+
// If there are elements present in the nodes then
37+
// make a new node for future addition otherwise we
38+
// will get unnecessary (0 --> <nil>) node in the end.
39+
if currentNode1 != nil || currentNode2 != nil {
40+
currentHead.Next = &ListNode{}
41+
currentHead = currentHead.Next
42+
} else if nextSum != 0 {
43+
// If nextSum is not 0 this means that there was some carry value
44+
// left in it which should be further.
45+
currentHead.Next = &ListNode{nextSum, nil}
46+
}
47+
} else {
48+
break
49+
}
50+
}
51+
52+
return head
53+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/*
2+
* Report by leetcode.com
3+
* Runtime: 8 ms, Memory Usage: 3.2 MB
4+
*/
5+
func lengthOfLongestSubstring(s string) int {
6+
mathMax := func(a, b int) int {
7+
if a > b {
8+
return a
9+
}
10+
return b
11+
}
12+
cache := map[rune]int{}
13+
var max, position int
14+
for i, r := range s {
15+
if num, ok := cache[r]; ok {
16+
position = mathMax(position, num+1)
17+
}
18+
cache[r] = i
19+
max = mathMax(max, i-position+1)
20+
}
21+
return max
22+
}

0 commit comments

Comments
 (0)
Please sign in to comment.