Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions Week 01/id_236/LeetCode_1_236.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package main

import "fmt"

// Solution 1: Brute-Force
// Use two loops to search the right pair.
// Time Complexity : O(n^2)
// Space Complexity: O(1)

// Solution 2: Sort and Search
// Sort the copied nums[O(NlogN)], and use two pointers start/end to search the pair[O(N)].
// And search the indices in the original array.
// Time Complexity : O(NlogN)
// Space Complexity: O(N)

// Solution 3: Hash Record
// Use hash map to record number and index in iterating the nums to finding the pair.
// Time Complexity : O(N)
// Space Complexity: O(N)
func twoSum(nums []int, target int) []int {
// num index
m := make(map[int]int)

for i, num := range nums {
j, exists := m[target-num]

if exists {
return []int{i, j}
}

m[num] = i
}

return nil
}

func main() {
fmt.Println(twoSum([]int{2, 7, 11, 15}, 9))
}
103 changes: 103 additions & 0 deletions Week 01/id_236/LeetCode_21_236.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package main

import (
"fmt"
"strings"
)

// Solution 1: Recursive Assignment.
// The code is much cleaner but not recommended in production code,
// which will cause stack overflow if the list is too long.
// Time Complexity : O(M+N)
// Space Complexity: O(1)
func mergeTwoListsRecursion(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}

if l1.Val < l2.Val {
l1.Next = mergeTwoListsRecursion(l1.Next, l2)
return l1
} else {
l2.Next = mergeTwoListsRecursion(l1, l2.Next)
return l2
}
}

// Solution 2: Interative Loop.
// Use a dummy node to simplify the interactive loop.
// Time Complexity : O(M+N)
// Space Complexity: O(1)
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
dummy := &ListNode{}
curr := dummy

for l1 != nil && l2 != nil {
if l1.Val < l2.Val {
curr.Next = l1
l1 = l1.Next
} else {
curr.Next = l2
l2 = l2.Next
}

curr = curr.Next
}

if l1 == nil {
curr.Next = l2
} else {
curr.Next = l1
}

return dummy.Next
}

type ListNode struct {
Val int
Next *ListNode
}

func (l *ListNode) String() string {
if l == nil {
return ""
}

var b strings.Builder
if l != nil {
b.WriteString(fmt.Sprintf("%d", l.Val))
}

for node := l.Next; node != nil; node = node.Next {
b.WriteString(fmt.Sprintf("->%d", node.Val))
}

return b.String()
}

func main() {
l1 := &ListNode{
Val: 1,
Next: &ListNode{
Val: 2,
Next: &ListNode{
Val: 4,
},
},
}

l2 := &ListNode{
Val: 1,
Next: &ListNode{
Val: 3,
Next: &ListNode{
Val: 4,
},
},
}

fmt.Println(mergeTwoLists(l1, l2))
}