1. 程式人生 > >LeetCode Top 100 Liked Questions in Golang(updating...)

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
}

相關推薦

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

LeetCode面試常見100題( TOP 100 Liked Questions

這篇文章是關於LeetCode Top 100 Liked Questions 的 專欄記錄,其中部分題目可能包括解題思路和多種優化解法。我把自己的思路都記錄在這裡,如果你看見了,請記得點個贊吧,蟹蟹【手動笑臉】。 目錄: 1、Two Su

Leetcode Top 100 思路與程式碼(Java)

第01-100題 【Leetcode-easy-1】 Two Sum 兩數之和 平生不識TwoSum,刷盡LeetCode也枉然 思路: 為了提高時間的複雜度,需要用空間來換,那麼就是說只能遍歷一個數字,那麼另一個數字呢,我們可以事先

[LeetCode]Top Interview Questions/Easy Collection/String to Integer (atoi)

Implement atoi which converts a string to an integer. The function first discards as many whitespace characters as necessary until

LeetCode(Top Interview Questions)——Array

(一)Remove Duplicates from Sorted Array Given a sorted array nums, remove the duplicates in-place suc

[leetcode-442-Find All Duplicates in an Array]

solution i++ it is runtime span col target ted other Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear t

[leetcode-515-Find Largest Value in Each Tree Row]

ron 遍歷 vector div spa cto int ges pop You need to find the largest value in each row of a binary tree. Example: Input: 1 / \ 3

[leetcode-438-Find All Anagrams in a String]

not plan english urn tco bst ice style ons Given a string s and a non-empty string p, find all the start indices of p‘s anagrams in s.Str

[leetcode-387-First Unique Character in a String]

cnblogs store let min tps lee fin leet count Given a string, find the first non-repeating character in it and return it‘s index. If it do

LeetCode】84. Largest Rectangle in Histogram——直方圖最大面積

the area 求解 技術分享 ges sent -s com col alt Given n non-negative integers representing the histogram‘s bar height where the width of each ba

[Leetcode] DP-- 467. Unique Substrings in Wraparound String

dup rep wrap abc sid pri ase logs urn Consider the string s to be the infinite wraparound string of "abcdefghijklmnopqrstuvwxyz", so s wi

leetcode--515. Find Largest Value in Each Tree Row

largest input http code poll() pro tps pub curl 1、問題描述 You need to find the largest value in each row of a binary tree. Example: Input:

[leetcode-671-Second Minimum Node In a Binary Tree]

lee n-n style span sub auto cond binary out Given a non-empty special binary tree consisting of nodes with the non-negative value, where

[LeetCode] 530. Minimum Absolute Difference in BST Java

lis https root ren str void init 搜索樹 dia 題目: Given a binary search tree with non-negative values, find the minimum absolute difference be

LeetCode 442. Find All Duplicates in an Array (在數組中找到所有的重復項)

nts ext leet 日期 lin dot 目標 input output Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and oth

LeetCode 378: Kth Smallest Element in Sorted Matrix

nta public ger kth binary pan for each ble contains 1. Use priority queue. Need to check whether one element has been double counted: cl

[LeetCode] Top K Frequent Words 前K個高頻詞

uniq plan leet val log pac highest desc odin Given a non-empty list of words, return the k most frequent elements. Your answer shou

[Leetcode]532. K-diff Pairs in an Array

elong lan ray 有一個 wiki xpl exce define code Given an array of integers and an integer k, you need to find the number of unique k-diff pai

leetCode-Find All Numbers Disappeared in an Array

mark extra do it false strong scrip xtra view style Description: Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), som

Leetcode 215: Kth Largest Element in an Array

arr start public code bsp private valid it is note Find the kth largest element in an unsorted array. Note that it is the kth largest ele