邓心一 7 年之前
父节点
当前提交
7242624e5d
共有 15 个文件被更改,包括 685 次插入6 次删除
  1. 1 1
      easy/121.go
  2. 48 0
      easy/122.go
  3. 68 0
      easy/125.go
  4. 32 0
      easy/136.go
  5. 48 0
      easy/141.js
  6. 108 0
      easy/155.go
  7. 64 0
      easy/160.js
  8. 36 0
      easy/167.go
  9. 30 0
      easy/168.go
  10. 39 0
      easy/169.go
  11. 17 0
      easy/171.go
  12. 32 0
      easy/172.go
  13. 43 0
      easy/189.go
  14. 62 3
      medium/12.go
  15. 57 2
      medium/2.go

+ 1 - 1
easy/121.go

@@ -20,7 +20,7 @@ func maxProfit(prices []int) int {
 func main() {
 	a1 := []int{1, 2, 3, 4, 5}
 	a2 := []int{5, 4, 3, 2, 1}
-	a3 := []int{7, 4, 3, 8, 1}
+	a3 := []int{8, 1}
 	fmt.Println(maxProfit(a1))
 	fmt.Println(maxProfit(a2))
 	fmt.Println(maxProfit(a3))

+ 48 - 0
easy/122.go

@@ -0,0 +1,48 @@
+package main
+
+import (
+	"fmt"
+)
+
+func maxProfitOld(prices []int) int {
+	last, cost, profit := -1<<31, 1<<31-1, 0
+	for _, v := range prices {
+		if v < last {
+			if last > cost {
+				// sell stock
+				profit += last - cost
+				// buy stock
+				cost = v
+			}
+		}
+		if v < cost {
+			// buy cheaper stock
+			cost = v
+		}
+		// store price of yestoday
+		last = v
+	}
+	// sell stock at last day
+	if last > cost {
+		profit += last - cost
+	}
+	return profit
+}
+
+// split into small pieces!
+func maxProfit(prices []int) int {
+	profit := 0
+	for i := 1; i < len(prices); i++ {
+		if prices[i] > prices[i-1] {
+			profit += prices[i] - prices[i-1]
+		}
+	}
+	return profit
+}
+
+func main() {
+	a1 := []int{1, 2, 3, 46, 1, 4, 1, 4, 5}
+	a2 := []int{2, 1}
+	fmt.Println(maxProfit(a1))
+	fmt.Println(maxProfit(a2))
+}

+ 68 - 0
easy/125.go

@@ -0,0 +1,68 @@
+package main
+
+import (
+	"fmt"
+	"strings"
+)
+
+func isPalindromeOld(s string) bool {
+	lower := strings.ToLower(s)
+	arr := make([]byte, 0)
+	for i := 0; i < len(lower); i++ {
+		if (lower[i] >= 'a' && lower[i] <= 'z') || (lower[i] >= '0' && lower[i] <= '9') {
+			arr = append(arr, lower[i])
+		}
+	}
+	for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {
+		if arr[i] != arr[j] {
+			return false
+		}
+	}
+	return true
+}
+
+func isAlphanum(c byte) bool {
+	lower := c >= 'a' && c <= 'z'
+	upper := c >= 'A' && c <= 'Z'
+	numeric := c >= '0' && c <= '9'
+	return lower || upper || numeric
+}
+
+func isEqual(a, b byte) bool {
+	if a >= 'a' && a <= 'z' {
+		a = a - 'a' + 'A'
+	}
+	if b >= 'a' && b <= 'z' {
+		b = b - 'a' + 'A'
+	}
+	return a == b
+}
+
+func isPalindrome(s string) bool {
+	if len(s) == 0 || len(s) == 1 {
+		return true
+	}
+	for beg, end := 0, len(s)-1; beg < end; {
+		if !isAlphanum(s[beg]) {
+			beg++
+			continue
+		}
+		if !isAlphanum(s[end]) {
+			end--
+			continue
+		}
+		if isEqual(s[beg], s[end]) {
+			beg++
+			end--
+		} else {
+			return false
+		}
+	}
+	return true
+}
+
+func main() {
+	fmt.Println(isPalindrome(""))
+	fmt.Println(isPalindrome("How are!! ! rawoh~"))
+	fmt.Println(isPalindrome("0P"))
+}

+ 32 - 0
easy/136.go

@@ -0,0 +1,32 @@
+package main
+
+import (
+	"fmt"
+)
+
+func singleNumberOld(nums []int) int {
+	m := make(map[int]int, 0)
+	for _, v := range nums {
+		if m[v] != 0 {
+			delete(m, v)
+		} else {
+			m[v] = 1
+		}
+	}
+	for k, _ := range m {
+		return k
+	}
+	return -1 << 31
+}
+
+func singleNumber(nums []int) int {
+	n := 0
+	for _, v := range nums {
+		n = n ^ v
+	}
+	return n
+}
+
+func main() {
+	fmt.Println(singleNumber([]int{1, 2, 3, 3, 2}))
+}

+ 48 - 0
easy/141.js

@@ -0,0 +1,48 @@
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val) {
+ *     this.val = val;
+ *     this.next = null;
+ * }
+ */
+
+function ListNode(val) {
+    this.val = val;
+    this.next = null;
+}
+
+/**
+ * @param {ListNode} head
+ * @return {boolean}
+ */
+var hasCycle = function(head) {
+    if (head === null || head.next === null) return false
+    let set = new Set()
+    let curr = head
+    set.add(curr)
+    curr = curr.next
+    for (;;) {
+        if (curr === null) return false
+        if (set.has(curr)) return true
+        set.add(curr)
+        curr = curr.next
+    }
+}
+
+function __main__() {
+    let n13 = new ListNode(3)
+    let n12 = new ListNode(3)
+    let n1 = new ListNode(1)
+    n1.next = n12
+    n12.next = n13
+    let n23 = new ListNode(3)
+    let n22 = new ListNode(3)
+    let n2 = new ListNode(1)
+    n23.next = n2
+    n2.next = n22
+    n22.next = n23
+    console.log(hasCycle(n1))
+    console.log(hasCycle(n2))
+}
+
+__main__()

+ 108 - 0
easy/155.go

@@ -0,0 +1,108 @@
+package main
+
+import (
+	"fmt"
+)
+
+type MinStackOld struct {
+	val []int
+	min []int
+	top int
+}
+
+/** initialize your data structure here. */
+func ConstructorOld() MinStackOld {
+	s := MinStackOld{make([]int, 0), make([]int, 0), -1}
+	return s
+}
+
+func (this *MinStackOld) Push(x int) {
+	this.val = append(this.val, x)
+	this.top++
+	idx := 0
+	for ; idx < this.top; idx++ {
+		if x > this.val[idx] {
+			break
+		}
+	}
+	this.min = append(this.min, 0)
+	copy(this.min[idx+1:this.top+1], this.min[idx:this.top])
+	this.min[idx] = x
+}
+
+func (this *MinStackOld) Pop() {
+	if this.top != -1 {
+		idx := 0
+		for ; idx < this.top+1; idx++ {
+			if this.min[idx] == this.val[this.top] {
+				break
+			}
+		}
+		this.min = append(this.min[:idx], this.min[idx+1:]...)
+		this.val = this.val[:this.top]
+		this.top--
+	}
+}
+
+func (this *MinStackOld) Top() int {
+	return this.val[this.top]
+}
+
+func (this *MinStackOld) GetMin() int {
+	return this.min[this.top]
+}
+
+/**
+ * Your MinStack object will be instantiated and called as such:
+ * obj := Constructor();
+ * obj.Push(x);
+ * obj.Pop();
+ * param_3 := obj.Top();
+ * param_4 := obj.GetMin();
+ */
+
+type MinStack struct {
+	val []int
+	min []int
+}
+
+/** initialize your data structure here. */
+func Constructor() MinStack {
+	return MinStack{}
+}
+
+// important! min []int stores the "current miximum"
+func (this *MinStack) Push(x int) {
+	this.val = append(this.val, x)
+	if len(this.min) == 0 {
+		this.min = append(this.min, x)
+		return
+	}
+	m := this.min[len(this.min)-1]
+	if x < m {
+		this.min = append(this.min, x)
+		return
+	}
+	this.min = append(this.min, m)
+}
+
+func (this *MinStack) Pop() {
+	n := len(this.val) - 1
+	this.val = this.val[:n]
+	this.min = this.min[:n]
+}
+
+func (this *MinStack) Top() int {
+	return this.val[len(this.val)-1]
+}
+
+func (this *MinStack) GetMin() int {
+	return this.min[len(this.min)-1]
+}
+
+func main() {
+	stack := Constructor()
+	stack.Push(1)
+	fmt.Println(stack.Top())
+	fmt.Println(stack.GetMin())
+}

+ 64 - 0
easy/160.js

@@ -0,0 +1,64 @@
+/**
+ * Definition for singly-linked list.
+ * function ListNode(val) {
+ *     this.val = val;
+ *     this.next = null;
+ * }
+ */
+
+function ListNode(val) {
+    this.val = val;
+    this.next = null;
+}
+
+/**
+ * @param {ListNode} headA
+ * @param {ListNode} headB
+ * @return {ListNode}
+ */
+var getIntersectionNode = function(headA, headB) {
+    let set = new Set()
+    let pA = headA, pB = headB
+    while (pA !== null && pB != null) {
+        if (set.has(pA)) return pA
+        set.add(pA)
+        if (set.has(pB)) return pB
+        set.add(pB)
+        pA = pA.next
+        pB = pB.next
+    }
+    if (pA === pB) return null
+    let curr = null
+    if (pA === null) {
+        curr = pB
+    } else {
+        curr = pA
+    }
+    while (curr !== null) {
+        if (set.has(curr)) return curr
+        set.add(curr)
+        curr = curr.next
+    }
+    return null
+};
+
+function __main__() {
+    let n2 = new ListNode(2)
+    let n22 = new ListNode(3)
+    let n23 = new ListNode(3)
+    let n24 = new ListNode(3)
+    n2.next = n22
+    n22.next = n23
+    n23.next = n24
+    let n1 = new ListNode(3)
+    let n12 = new ListNode(3)
+    let n13 = new ListNode(3)
+    n1.next = n12
+    n12.next = n13
+    n24.next = n12
+    let n3 = new ListNode(3)    
+    console.log(getIntersectionNode(n1, n2))
+    console.log(getIntersectionNode(n2, n3))
+}
+
+__main__()

+ 36 - 0
easy/167.go

@@ -0,0 +1,36 @@
+package main
+
+import (
+	"fmt"
+)
+
+func twoSumOld(numbers []int, target int) []int {
+	for i := 0; i < len(numbers)-1; i++ {
+		for j := i + 1; j < len(numbers); j++ {
+			if numbers[i]+numbers[j] == target {
+				return []int{i + 1, j + 1}
+			}
+		}
+	}
+	return nil
+}
+
+func twoSum(numbers []int, target int) []int {
+	left, right := 0, len(numbers)-1
+	for left != right {
+		sum := numbers[left] + numbers[right]
+		if sum < target {
+			left++
+		} else if sum > target {
+			right--
+		} else {
+			return []int{left + 1, right + 1}
+		}
+	}
+	return nil
+}
+
+func main() {
+	arr := []int{-1, 0}
+	fmt.Println(twoSum(arr, -1))
+}

+ 30 - 0
easy/168.go

@@ -0,0 +1,30 @@
+package main
+
+import (
+	"fmt"
+)
+
+// wtf
+func convertToTitleOld(n int) string {
+	if n == 0 {
+		return ""
+	}
+	return convertToTitleOld((n-1)/26) + string(rune((n-1)%26+'A'))
+}
+
+func convertToTitle(n int) string {
+	var res string
+	for n != 0 {
+		n--
+		res = string('A'+n%26) + res
+		n /= 26
+	}
+	return res
+} // A --> 0, Z --> 25 !!!
+
+func main() {
+	fmt.Println(convertToTitle(546))
+	fmt.Println(convertToTitle(26))
+	fmt.Println(convertToTitle(702))
+	fmt.Println(convertToTitle(676))
+}

+ 39 - 0
easy/169.go

@@ -0,0 +1,39 @@
+package main
+
+import (
+	"fmt"
+)
+
+func majorityElementOld(nums []int) int {
+	m := map[int]int{}
+	n := int(len(nums) / 2)
+	for _, v := range nums {
+		m[v]++
+		if m[v] > n {
+			return v
+		}
+	}
+	return 0
+}
+
+// ~ little trick
+func majorityElement(nums []int) int {
+	var cnt = 0
+	var num int
+	for _, v := range nums {
+		if cnt == 0 {
+			num = v
+		}
+		if v == num {
+			cnt++
+		} else {
+			cnt--
+		}
+	}
+	return num
+}
+
+func main() {
+	arr := []int{1, 1, 3}
+	fmt.Println(majorityElement(arr))
+}

+ 17 - 0
easy/171.go

@@ -0,0 +1,17 @@
+package main
+
+import (
+	"fmt"
+)
+
+func titleToNumber(s string) int {
+	res := 0
+	for base, i := 1, len(s)-1; i >= 0; base, i = base*26, i-1 {
+		res += base * int(s[i]-'A'+1)
+	}
+	return res
+}
+
+func main() {
+	fmt.Println(titleToNumber("WV"))
+}

+ 32 - 0
easy/172.go

@@ -0,0 +1,32 @@
+package main
+
+import (
+	"fmt"
+	"math"
+)
+
+// ???
+func trailingZeroesOld(n int) int {
+	cnt := 0
+	for i := 5; i <= n; i += 5 {
+		cnt += int(math.Log(float64(i)) / math.Log(5))
+	}
+	return cnt
+}
+
+func trailingZeroes(n int) int {
+	var res int
+	for n > 0 {
+		n /= 5
+		res += n
+	}
+	return res
+}
+
+func main() {
+	fmt.Println(trailingZeroes(3))
+	fmt.Println(trailingZeroes(7))
+	fmt.Println(trailingZeroes(10))
+	fmt.Println(trailingZeroes(100))
+	fmt.Println(int(math.Log10(float64(125)) / math.Log10(5)))
+}

+ 43 - 0
easy/189.go

@@ -0,0 +1,43 @@
+package main
+
+import (
+	"fmt"
+)
+
+func rotate1st(nums []int, k int) {
+	n := len(nums)
+	tmp := append(nums[n-k:], nums[:n-k]...)
+	copy(nums, tmp)
+}
+
+func rotate2nd(nums []int, k int) {
+	tmp := make([]int, len(nums))
+	copy(tmp, nums)
+	n := len(nums)
+	for i, v := range tmp {
+		idx := (i + k) % n
+		nums[idx] = v
+	}
+}
+
+func rotate3rd(nums []int, k int) {
+	n := len(nums)
+	// [1 2 3] -> [3 2 1]
+	for i, j := 0, n-k-1; i < j; i, j = i+1, j-1 {
+		nums[i], nums[j] = nums[j], nums[i]
+	}
+	// [4 5 6 7] -> [7 6 5 4]
+	for i, j := n-k, n-1; i < j; i, j = i+1, j-1 {
+		nums[i], nums[j] = nums[j], nums[i]
+	}
+	// [3 2 1 7 6 5 4] -> [4 5 6 7 1 2 3]
+	for i, j := 0, n-1; i < j; i, j = i+1, j-1 {
+		nums[i], nums[j] = nums[j], nums[i]
+	}
+}
+
+func main() {
+	arr := []int{1, 2, 3, 4, 5, 6, 7}
+	rotate1st(arr, 4)
+	fmt.Println(arr)
+}

+ 62 - 3
medium/12.go

@@ -1,6 +1,12 @@
 package main
 
-var mRoman = map[int]rune{
+import (
+	"bytes"
+	"fmt"
+	"math"
+)
+
+var mRoman = map[float64]rune{
 	1:    'I',
 	5:    'V',
 	10:   'X',
@@ -10,11 +16,64 @@ var mRoman = map[int]rune{
 	1000: 'M',
 }
 
-func intToRoman(num int) string {
+func digitToRoman(pos, digit int) []rune {
+	res := make([]rune, 0)
+	base := math.Pow10(pos)
+	switch digit {
+	case 0:
+	case 1:
+		fallthrough
+	case 2:
+		fallthrough
+	case 3:
+		for i := 0; i < digit; i++ {
+			res = append(res, mRoman[base])
+		}
+	case 4:
+		res = append(res, mRoman[base], mRoman[base*5])
+	case 5:
+		fallthrough
+	case 6:
+		fallthrough
+	case 7:
+		fallthrough
+	case 8:
+		res = append(res, mRoman[base*5])
+		for i := 5; i < digit; i++ {
+			res = append(res, mRoman[base])
+		}
+	case 9:
+		res = append(res, mRoman[base], mRoman[base*10])
+	default:
+	}
+	return res
+}
+
+func intToRomanOld(num int) string {
 	res := make([]rune, 0)
+	for i := 0; num != 0; i, num = i+1, num/10 {
+		roman := digitToRoman(i, num%10)
+		res = append(roman, res...)
+	}
 	return string(res)
 }
 
-func main() {
+var roman = [4][10]string{
+	{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
+	{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
+	{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
+	{"", "M", "MM", "MMM"},
+}
 
+func intToRoman(num int) string {
+	var res bytes.Buffer
+	res.WriteString(roman[3][num/1000])
+	res.WriteString(roman[2][num%1000/100])
+	res.WriteString(roman[1][num%100/10])
+	res.WriteString(roman[0][num%10])
+	return res.String()
+}
+
+func main() {
+	fmt.Println(intToRoman(1998))
 }

+ 57 - 2
medium/2.go

@@ -1,5 +1,24 @@
 package main
 
+import (
+	"fmt"
+)
+
+type ListNode struct {
+	Val  int
+	Next *ListNode
+}
+
+func list2str(head *ListNode) string {
+	curr := head
+	str := make([]rune, 0)
+	for curr != nil {
+		str = append(str, rune(curr.Val+'0'))
+		curr = curr.Next
+	}
+	return string(str)
+}
+
 /**
  * Definition for singly-linked list.
  * type ListNode struct {
@@ -23,15 +42,16 @@ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
 		l1 = l1.Next
 		l2 = l2.Next
 	}
-	// l1 / l2 is nil
+	// l1 / l2 is nil (l1 == nil, l2 == nil, do nothing)
 	if l1 != nil {
 		curr.Next = &ListNode{(l1.Val + remain) % 10, l1.Next}
 		remain = int((l1.Val + remain) / 10)
+		curr = curr.Next
 	} else if l2 != nil {
 		curr.Next = &ListNode{(l2.Val + remain) % 10, l2.Next}
 		remain = int((l2.Val + remain) / 10)
+		curr = curr.Next
 	}
-	curr = curr.Next
 	// add remainder
 	for remain != 0 {
 		if curr.Next != nil {
@@ -46,3 +66,38 @@ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
 	}
 	return head
 }
+
+func list2int(head *ListNode) int64 {
+	beg := head
+	res := int64(0)
+	for i := 1; beg != nil; i *= 10 {
+		res += int64(beg.Val * i)
+		beg = beg.Next
+	}
+	return res
+}
+
+func int2list(num int64) *ListNode {
+	head := &ListNode{int(num % 10), nil}
+	num /= 10
+	for tail := head; num != 0; num /= 10 {
+		tail.Next = &ListNode{int(num % 10), nil}
+		tail = tail.Next
+	}
+	return head
+}
+
+// will overflow
+func addTwoNumbersOld(l1 *ListNode, l2 *ListNode) *ListNode {
+	return int2list(list2int(l1) + list2int(l2))
+}
+
+func main() {
+	l13 := ListNode{3, nil}
+	l12 := ListNode{2, &l13}
+	l1 := &ListNode{1, &l12}
+	l23 := ListNode{9, nil}
+	l22 := ListNode{9, &l23}
+	l2 := &ListNode{1, &l22}
+	fmt.Println(list2str(addTwoNumbers(l1, l2)))
+}