java程序猿转go语言,通过leetcode刷题来熟悉go语言,完成语言基础和语法基础的熟悉

1.两数之和

暴力破解:

func twoSum(nums []int, target int) []int {
    for i := 0; i < len(nums) - 1; i++ {
        for j := i + 1; j < len(nums); j++ {
            if (nums[j] + nums[i] == target) {
                return []int {i, j};
            }
        }
    }
    return nil
}

哈希表:

func twoSum(nums []int, target int) []int {
    hashmap := make(map[int] int)
    for index, value := range nums {
        if v, ok := hashmap[value]; ok {
            return []int{index, v}
        }
        hashmap[target - value] = index
    }
    return nil
}

2.两数相加

递归版本(链表或者树的问题都要尽量想一个递归的)

 func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    return addTwoNumbersHelp(l1, l2, 0);
}
func addTwoNumbersHelp(l1 *ListNode, l2 *ListNode, add int) *ListNode {
   if l1 == nil && l2 == nil && add == 0 {
      return nil
 }
   if (l1 != nil) {
      add = l1.Val + add;
      l1 = l1.Next
 }
   if (l2 != nil) {
      add = l2.Val + add;
      l2 = l2.Next
 }
   node := ListNode{
      add % 10,
      addTwoNumbersHelp(l1, l2, add / 10),
   }
   return &node;
}

非递归版本

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
    head := ListNode{};
    tail := &head;
    add := 0;
    for l1 != nil && l2 != nil {
        add += l1.Val + l2.Val;
        l1 = l1.Next;
        l2 = l2.Next;
        cur := ListNode{
            Val: add % 10,
            Next: nil,
        }
        tail.Next = &cur;
        tail = &cur;
        add = add / 10;
    }
    for l1 != nil {
        add += l1.Val;
        l1 = l1.Next;
        cur := ListNode{
            Val: add % 10,
            Next: nil,
        }
        tail.Next = &cur;
        tail = &cur;
        add = add / 10;
    }
    for l2 != nil {
        add += l2.Val;
        l2 = l2.Next;
        cur := ListNode{
            Val: add % 10,
            Next: nil,
        }
        tail.Next = &cur;
        tail = &cur;
        add = add / 10;
    }
    if add != 0 {
        tail.Next = &ListNode{1,nil}
    }
    return head.Next;
}

3.最长无重复子串

直观的逻辑:哈希表记录字符存在的下标、如果存在过,则左边界等于原本左边界或者重复的字符的位置+1的位置中较大的,因为有可能重复字符不在如今最长子串的范围里,则左边界无需变化

func lengthOfLongestSubstring1(s string) int {
   res := 0;
   m := make(map[byte] int);
   left := 0;
   for i := 0; i < len(s); i++ {
      if _,ok := m[s[i]]; ok {
         left = int(math.Max(float64(left), float64(m[s[i]]+1)));
      }
      m[s[i]] = i;
      res = int(math.Max(float64(res), float64(i-left+1)))
   }
   return res;
}

巧妙的只增大不减小窗口

func lengthOfLongestSubstring(s string) int {
    start,end := 0,0
    for i := 0; i < len(s); i++ {
        index := strings.Index(s[start:i],string(s[i]))
        if index==-1{
            if i+1>end{
                end=i+1
            } 
        }else{
                start+=index+1
                end+=index+1
            }
    }
    return end-start
}

image


彩笔梳子
10 声望2 粉丝