LeetCode Top 100 Liked Questions in Golang(updating...)
leetcode go语言版本,主要为了熟悉下语言
1. Two Sum
双指针版本, O(NlogN)
func twoSum(nums []int, target int) []int { valResult := []int{} indexResult := []int{} i := 0 j := len(nums) - 1 temp := make([]int, len(nums)) copy(temp, nums) sort.Ints(temp) for i < j { if temp[i] + temp[j] < target { i++ } else if temp[i] + temp[j] > target { j-- } else { valResult = append(valResult, temp[i], temp[j]) break } } for i := 0; i < len(nums); i++ { if nums[i] == valResult[0] || nums[i] == valResult[1] { indexResult = append(indexResult, i) } } return indexResult }
hash查找版本,理论O(N)
func twoSum(nums []int, target int) []int { hash := make(map[int]int) result := []int{} for i := 0; i < len(nums); i++ { if j, ok := hash[target - nums[i]]; ok { result = append(result, j, i) return result } hash[nums[i]] = i } return result }
2. Add Two Numbers
要想办法把代码写简洁...不要好几个循环判断...
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } */ func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode { dummy := ListNode{} p := &dummy carry := 0 for l1 != nil || l2 != nil || carry != 0 { p.Next = &ListNode{} p = p.Next tempVal := carry if l1 != nil { tempVal += l1.Val l1 = l1.Next } if l2 != nil { tempVal += l2.Val l2 = l2.Next } p.Val = tempVal % 10 carry = tempVal / 10 } return dummy.Next }
3. Longest Substring Without Repeating Characters
hash里面存byte可解决英文字符,存rune中文也可处理...
func lengthOfLongestSubstring(s string) int { hash := make(map[rune]int) left := 0 result := 0 for i, v := range []rune(s) { if lastI, ok := hash[v]; ok && lastI >= left { left = lastI + 1 } if result < (i - left + 1) { result = i - left + 1 } hash[v] = i } return result }