344. Reverse String
Write a function that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. You may assume all the characters consist of printable ascii characters.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
Example 2:
Example 2:
Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a","H"]
Solution
func reverseString(s []byte) {
if len(s) == 0 {
return
}
length := len(s)
head := 0
end := length - 1
for ; head < length/2 ; {
s[head], s[end] = s[end], s[head]
head++
end--
}
}
Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note:
A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its depth = 3.
Solution
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
if root.Left == nil && root.Right == nil {
return 1
}
return maxDepthRec(root, 0)
}
func maxDepthRec(current *TreeNode, depth int) int {
if current == nil {
return depth
}
if current.Left == nil && current.Right == nil {
return depth + 1
}
rightDepth := depth
leftDepth := depth
if current.Left != nil {
rightDepth = maxDepthRec(current.Left, depth + 1)
}
if current.Right != nil {
leftDepth = maxDepthRec(current.Right, depth + 1)
}
if rightDepth > leftDepth {
return rightDepth
}
return leftDepth
}
- Single Number
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
Solution
func singleNumber(nums []int) int {
if len(nums) == 1{
return nums[0]
}
result := nums[0]
length := len(nums)
for index:=1;index < length; index++ {
result = result ^ nums[index]
}
return result
}
- Fizz Buzz
Write a program that outputs the string representation of numbers from 1 to n. But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
Example:
n = 15,
Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]
Solution:
import "strconv"
func fizzBuzz(n int) []string {
var result []string
for i := 1; i <= n; i++ {
switch {
case i%15 == 0:
result = append(result, "FizzBuzz")
case i%3 == 0:
result = append(result, "Fizz")
case i%5 == 0:
result = append(result, "Buzz")
default:
num := strconv.Itoa(i)
result = append(result, num)
}
}
return result
}
237. Delete Node in a Linked
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.Given linked list -- head = [4,5,1,9], which looks like following:
4 --> 1 --> 5 --> 9
Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
Example 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
Note:
The linked list will have at least two elements. All of the nodes' values will be unique. The given node will not be the tail and it will always be a valid node of the linked list. Do not return anything from your function.
Solution:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func deleteNode(node *ListNode) {
node.Val, node.Next = node.Next.Val, node.Next.Next
}
206. Reverse Linked List
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
Solution:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
if head == nil {
return nil
}
if head.Next == nil {
return head
}
p1 := head
p2 := head.Next
p3 := head.Next.Next
p1.Next = nil
return reverseRec(p1, p2, p3)
}
func reverseRec(prev *ListNode, cur *ListNode, next *ListNode) *ListNode {
// end condition
if next == nil {
cur.Next = prev
return cur
}
//reverse
tmp := cur
cur.Next = prev
prev = tmp
cur = next
next = next.Next
// recursive
return reverseRec(prev, cur, next)
}
169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than
⌊ n/2 ⌋times. You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
Solution:
import "sort"
func majorityElement(nums []int) int {
if len(nums) == 1 {
return nums[0]
}
// quick sort the array then return middle element
sort.Ints(nums) // ascend
return nums[len(nums) / 2]
}
func majorityElement(nums []int) int {
cnt := 0
major := nums[0]
length := len(nums)
for i:=0 ; i < length; i++ {
if nums[i] == major {
cnt++
continue
} else if cnt > 0 {
cnt--
continue
}
major = nums[i]
}
return major
}
283. Move Zeroes
Given an array
nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array. Minimize the total number of operations.
func moveZeroes(nums []int) {
if len(nums) <= 1 {
return
}
length := len(nums)
for i:=0; i < length; i++ {
if nums[i] != 0 {
continue
}
iZero := i+1
if iZero >= length {
break
}
for ; iZero < length; {
if nums[iZero] != 0 {
// swap 0 and non-0
nums[i], nums[iZero] = nums[iZero], nums[i]
break
}
iZero++
}
}
}
108. Convert Sorted Array to Binary Search Tree
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example:
Given the sorted array: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
Solution:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func sortedArrayToBST(nums []int) *TreeNode {
if len(nums) == 0 {
return nil
}
if len(nums) == 1 {
node := new(TreeNode)
node.Val=nums[0]
return node
}
return createBST(nums, 0, len(nums)-1)
}
func createBST(nums []int, left int, right int) *TreeNode {
// border
if left > right || left < 0 || right >= len(nums) {
return nil
}
node := new(TreeNode)
middle := (left + right)/2
node.Val = nums[middle]
node.Right = createBST(nums, middle + 1, right)
node.Left = createBST(nums, left, middle-1)
return node
}
122. Best Time to Buy and Sell Stock II
Say you have an array prices for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
Constraints:
1 <= prices.length <= 3 * 10 ^ 4
0 <= prices[i] <= 10 ^ 4
Solutions
暴力穷举法 (不符合时间限制)
func maxProfit(prices []int) int {
if len(prices) < 2 {
return 0
}
return maxProfitRec(prices, 0, 0, false)
}
// 暴力穷举法
func maxProfitRec(prices []int, cur int, profit int, hold bool) int {
if cur == len(prices) - 1 {
// 最后一天持有,则卖出
if hold {
return profit + prices[cur]
}
return profit
}
// 如果,持有, 尝试卖出或者是不卖;
if hold {
sell := maxProfitRec(prices, cur+1, profit+prices[cur], false)
hold := maxProfitRec(prices, cur+1, profit, true)
return max(sell, hold)
}
// 如果,未持有,尝试买入或者是不卖;
buy := maxProfitRec(prices, cur+1, profit-prices[cur], true)
wait := maxProfitRec(prices, cur+1, profit, false)
return max(buy, wait)
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
模型抽象,增长曲线落差和
func maxProfit(prices []int) int {
if len(prices) < 2 {
return 0
}
tmpBottom := int(^uint(0) >> 1) // MaxInt in Go
sum := 0
length := len(prices)
for i:=0; i < length; i++ {
if prices[i] < tmpBottom {
tmpBottom = prices[i]
continue
}
sum += prices[i] - tmpBottom
tmpBottom = prices[i]
}
return sum
}
Optimized:
func maxProfit(prices []int) int {
max := 0
for i := 1; i < len(prices); i ++ {
if prices[i] > prices[i - 1] {
max += prices[i] - prices[i - 1]
}
}
return max
}
242. Valid Anagram
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.
Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
Solution
func isAnagram(s string, t string) bool {
if len(s) != len(t) {
return false
}
a1 := [26]int{}
a2 := [26]int{}
// go语言中的字符串实际上是类型为byte的只读切片
for _, a := range s {
index := int(a) - 97
a1[index]++
}
for _, b := range t {
index := int(b) - 97
a2[index]++
}
for i, a := range a1 {
if a2[i] != a {
return false
}
}
return true
}
217. Contains Duplicate
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
Example 1:
Input: [1,2,3,1]
Output: true
Example 2:
Input: [1,2,3,4]
Output: false
Example 3:
Input: [1,1,1,3,3,4,3,2,4,2]
Output: true
Solution
空间优先
import "sort"
func containsDuplicate(nums []int) bool {
if nums == nil {
return false
}
sort.Ints(nums)
for i:=0; i<len(nums)-1; i++ {
if nums[i] == nums[i+1] {
return true
}
}
return false
}
时间优先
func containsDuplicate(nums []int) bool {
show := make(map[int]bool)
for _, n := range nums {
if show[n] {
return true
} else {
show[n] = true
}
}
return false
}
13. Roman to Integer
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
Symbol Value I 1 V 5 X 10 L 50 C 100 D 500 M 1000For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six
instances where subtraction is used:
Ican be placed beforeV(5) andX(10) to make 4 and 9.Xcan be placed beforeL(50) andC(100) to make 40 and 90.Ccan be placed beforeD(500) andM(1000) to make 400 and 900.
Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: "III"
Output: 3
Example 2:
Input: "IV"
Output: 4
Example 3:
Input: "IX"
Output: 9
Example 4:
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Solution:
注意Golang独有的byte和string类型的定义和互相转化
func romanToInt(s string) int {
numMap := map[byte]int {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000,
}
res := 0
for i := 0; i<len(s); i++{
if i != len(s)-1 && numMap[s[i]] < numMap[s[i+1]] {
res -= numMap[s[i]]
} else {
res += numMap[s[i]]
}
}
return res
}
#171. Excel Sheet Column Number
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
Example 1:
Input: "A"
Output: 1
Example 2:
Input: "AB"
Output: 28
Example 3:
Input: "ZY"
Output: 701
Constraints:
- 1 <= s.length <= 7
- s consists only of uppercase English letters.
- s is between "A" and "FXSHRXW".
Solution
func titleToNumber(s string) int {
sum := 0
length := len(s)
for index, num := range s {
n := int(num) - 64
m := length - index - 1
sum += (pow(26, m) * n)
}
return sum
}
func pow(x int, y int) int {
result := 1
for ; y > 0 ; y-- {
result *= x
}
return result
}
387. First Unique Character in a String
Given a string, find the first non-repeating character in it and return its index. If it doesn't exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode"
return 2.
Note: You may assume the string contains only lowercase English letters.
func firstUniqChar(s string) int {
if len(s) < 1 {
return -1
}
if len(s) == 1 {
return 0
}
charAppear := [26]int{}
charFirst := [26]int{}
result := len(s)
for i, c := range s {
n := int(c) - 97
if charAppear[n] == 0 {
charFirst[n] = i
}
charAppear[n]++
}
for i, b := range charAppear {
if b == 1 && charFirst[i] < result {
result = charFirst[i]
}
}
if result == len(s) {
return -1
}
return result
}
21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
Solution:
**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
head := new(ListNode)
current := head
for l1 !=nil && l2 !=nil {
if l1.Val > l2.Val {
current.Next = l2
current = current.Next
l2 = l2.Next
continue
}
current.Next = l1
current = current.Next
l1 = l1.Next
}
if l1 != nil {
current.Next = l1
}
if l2 != nil {
current.Next = l2
}
return head.Next
}
118. Pascal's Triangle
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Solution:
func generate(numRows int) [][]int {
if numRows == 0 {
return [][]int{}
}
result := [][]int{}
result = append(result, []int{1})
for i:=1;i<=numRows;i++{
item := []int{}
for j:=0;j<i;j++{
if j == 0 || j == i-1{
item = append(item, 1)
continue
}
num := result[i-1][j-1] + result[i-1][j]
item = append(item, num)
}
result = append(result, item)
}
return result[1:]
}
268. Missing Number
Given an array containing n distinct numbers taken from
0, 1, 2, ..., n, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
func missingNumber(nums []int) int {
expected := len(nums)*(1+len(nums))/2
sum := 0
for _, n := range nums {
sum += n
}
return (expected - sum)
}
350. Intersection of Two Arrays II
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Note:
Each element in the result should appear as many times as it shows in both arrays. The result can be in any order.
Follow up:
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1's size is small compared to nums2's size? Which algorithm is better?
- What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
Solution:
func intersect(nums1 []int, nums2 []int) []int {
result := []int{}
inter := make(map[int]int)
for _, n := range nums1 {
inter[n]++
}
for _, m := range nums2 {
if _, ok := inter[m]; ok && inter[m] > 0 {
result = append(result, m)
inter[m] -= 1
}
if inter[m] < 1 {
delete(inter, m)
}
}
return result
}
371. Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator
+and-.
Example 1:
Input: a = 1, b = 2
Output: 3
Example 2:
Input: a = -2, b = 3
Output: 1
func getSum(a int, b int) int {
// 进行到没有进位为止
for b != 0 {
r, c := a ^ b, (a & b) << 1
a, b = r, c
}
return a
}
121. Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Not 7-1 = 6, as selling price needs to be larger than buying price.
Example 2:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
Solution:
func maxProfit(prices []int) int {
minPrice := int(^uint(0) >> 1)
maxProfit := 0
for _, n := range prices {
if n < minPrice {
minPrice = n
continue
}
tmpProfit := n - minPrice
if tmpProfit > maxProfit {
maxProfit = tmpProfit
continue
}
}
return maxProfit
}
202. Happy Number
Write an algorithm to determine if a number n is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Return True if n is a happy number, and False if not.
**Example: **
Input: 19
Output: true
Explanation:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
Solution:
func isHappy(n int) bool {
appear := make(map[int]bool)
for n != 1 {
if _, ok := appear[n]; ok {
return false
}
appear[n] = true
sum := 0
tmp := n
for tmp > 0 {
d := tmp % 10
tmp = tmp / 10
sum += (d * d)
}
n = sum
}
return true
}
191. Number of 1 Bits
Write a function that takes an unsigned integer and return the number of '1' bits it has (also known as the Hamming weight).
Example 1:
Input: 00000000000000000000000000001011
Output: 3
Explanation: The input binary string 00000000000000000000000000001011 has a total of three '1' bits.
Example 2:
Input: 00000000000000000000000010000000
Output: 1
Explanation: The input binary string 00000000000000000000000010000000 has a total of one '1' bit.
Example 3:
Input: 11111111111111111111111111111101
Output: 31
Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one '1' bits.
Solution:
func hammingWeight(num uint32) int {
sum := 0
for num != 0 {
sum ++
num = num & (num-1)
}
return sum
}
70. Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
Constraints:
- 1 <= n <= 45
Solution
func climbStairs(n int) int {
if n == 0 {
return 0
}
if n == 1 {
return 1
}
if n == 2 {
return 2
}
prev, cur := 1, 2
for i := 2;i < n; i++ {
prev, cur = cur, (prev + cur)
}
return cur
}
101. Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3
Follow up: Solve it both recursively and iteratively.
iteratively
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isSymmetric(root *TreeNode) bool {
current := []*TreeNode{root}
for len(current) != 0 {
next := []*TreeNode{}
for _, node := range current {
if node == nil {
continue
}
if node.Left != nil {
next = append(next, node.Left)
} else {
next = append(next, nil)
}
if node.Right != nil {
next = append(next, node.Right)
} else {
next = append(next, nil)
}
}
start := 0
end := len(next) - 1
for start < end {
if next[start] == nil && next[end] == nil {
start++
end--
continue
}
if next[start] == nil && next[end] != nil {
return false
}
if next[start] != nil && next[end] == nil {
return false
}
if next[start].Val != next[end].Val {
return false
}
start++
end --
}
current = next
}
return true
}
recursively
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isSymmetric(root *TreeNode) bool {
return isSymmetricRec([]*TreeNode{root})
}
func isSymmetricRec(current []*TreeNode) bool {
if len(current) == 0 {
return true
}
next := []*TreeNode{}
start := 0
end := len(current) - 1
for start < end {
// judge symmetric
if current[start] == nil && current[end] ==nil {
start++
end--
continue
}
if current[start] == nil && current[end] != nil {
return false
}
if current[start] != nil && current[end] == nil {
return false
}
if current[start].Val != current[end].Val {
return false
}
start ++
end --
}
for _, node := range current {
if node == nil {
continue
}
if node.Left != nil {
next = append(next, node.Left)
} else {
next = append(next, nil)
}
if node.Right != nil {
next = append(next, node.Right)
} else {
next = append(next, nil)
}
}
return isSymmetricRec(next)
}
53. Maximum Subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Solution
func maxSubArray(nums []int) int {
gMax := nums[0]
curMax := nums[0]
for i := 1 ; i < len(nums); i++ {
curMax = max(curMax + nums[i], nums[i])
if curMax > gMax {
gMax = curMax
}
}
return gMax
}
func max(x int, y int) int {
if x > y {
return x
}
return y
}
LeeCode Solution
leetcode-cn.com/problems/ma…
func maxSubArray(nums []int) int {
return get(nums, 0, len(nums) - 1).mSum;
}
func pushUp(l, r Status) Status {
iSum := l.iSum + r.iSum
lSum := max(l.lSum, l.iSum + r.lSum)
rSum := max(r.rSum, r.iSum + l.rSum)
mSum := max(max(l.mSum, r.mSum), l.rSum + r.lSum)
return Status{lSum, rSum, mSum, iSum}
}
func get(nums []int, l, r int) Status {
if (l == r) {
return Status{nums[l], nums[l], nums[l], nums[l]}
}
m := (l + r) >> 1
lSub := get(nums, l, m)
rSub := get(nums, m + 1, r)
return pushUp(lSub, rSub)
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
type Status struct {
lSum, rSum, mSum, iSum int
}
1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Solution
/*
需要注意的Case
[-3,4,3,90] 0
[3,2,4] 6
*/
func twoSum(nums []int, target int) []int {
appear := make(map[int]int)
for i, n := range nums {
another := target -n
if _, ok := appear[another]; ok {
return []int{appear[another], i}
}
appear[n] = i
}
return []int{}
}
26. Remove Duplicates from Sorted Array
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
Solution:
// TODO: Optimization
func removeDuplicates(nums []int) int {
if len(nums) < 1 {
return len(nums)
}
cur := nums[0]
// start := 0
for i:=1; i < len(nums); i++ {
n := nums[i]
if cur != n {
cur = n
continue
}
nums = append(nums[:i], nums[i+1:] ...)
i -= 1
}
return len(nums)
}
155. Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
Constraints:
- Methods pop, top and getMin operations will always be called on non-empty stacks.
Solution
type MinStack struct {
Stack []int
}
/** initialize your data structure here. */
func Constructor() MinStack {
stack := new(MinStack)
return *stack
}
func (this *MinStack) Push(x int) {
this.Stack = append(this.Stack, x)
}
func (this *MinStack) Pop() {
if len(this.Stack) > 0 {
lastIndex := len(this.Stack) -1
this.Stack = this.Stack[:lastIndex]
return
}
panic("Emtpy Stack has nothing to pop")
}
func (this *MinStack) Top() int {
if len(this.Stack) > 0 {
return this.Stack[len(this.Stack)-1]
}
panic("Emtpy Stack has no Top")
}
func (this *MinStack) GetMin() int {
if len(this.Stack) > 0 {
min := this.Stack[0]
for _, n := range this.Stack {
if min > n {
min = n
}
}
return min
}
panic("Emtpy Stack has no Min")
}
/**
* 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();
*/
Optimized
const maxInt = math.MaxInt64
type MinStack struct {
stack []int
minStack []int
}
func Constructor() MinStack {
m := &MinStack{}
return *m
}
func (m *MinStack) Push(x int) {
m.stack = append(m.stack, x)
if len(m.minStack) == 0 || x <= m.minStack[len(m.minStack)-1] {
m.minStack = append(m.minStack, x)
}
}
func (m *MinStack) Pop() {
var x int
l := len(m.stack)
minl := len(m.minStack)
x, m.stack = m.stack[l-1], m.stack[:l-1]
if x == m.minStack[minl-1] {
m.minStack = m.minStack[:minl-1]
}
}
func (m *MinStack) Top() int {
return m.stack[len(m.stack)-1]
}
func (m *MinStack) GetMin() int {
return m.minStack[len(m.minStack)-1]
}
66. Plus One
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Solutiono:
func plusOne(digits []int) []int {
if len(digits) < 1 {
return []int{1}
}
index := len(digits) - 1
carry := 0
for ;index >=0; index-- {
current := 0
if index == len(digits) - 1 {
current = 1 + digits[index]
} else {
current = carry + digits[index]
}
if current > 9 {
digits[index] = current - 10
carry = 1
continue
} else {
digits[index] = current
carry = 0
continue
}
}
if carry == 1 {
digits = append([]int{1}, digits ...)
}
return digits
}
326. Power of Three
Given an integer, write a function to determine if it is a power of three.
Example 1:
Input: 27
Output: true
Example 2:
Input: 0
Output: false
Example 3:
Input: 9
Output: true
Example 4:
Input: 45
Output: false
Follow up:
Could you do it without using any loop / recursion?
Solution
func isPowerOfThree(n int) bool {
a := 1
for a < n {
a *= 3
}
return a == n
}
Optimized
if n <= 0 {
return false
}
for n > 1 {
if n % 3 != 0 {
return false
}
n /= 3
}
return true
Robber House
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
Constraints:
0 <= nums.length <= 1000 <= nums[i] <= 400
func rob(nums []int) int {
rob1 := 0
rob2 := 0
for i:=0; i < len(nums); i++ {
/*考虑当前策略和上面一步策略那个结果更优,取最优解*/
if i % 2 == 0 {
rob1 = max((rob1 + nums[i]), rob2)
} else {
rob2 = max((rob2 + nums[i]), rob1)
}
}
return max(rob1, rob2)
}
func max(x int, y int) int {
if x < y {
return y
} else {
return x
}
}
141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Follow up:
Can you solve it using O(1) (i.e. constant) memory?
Solution:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func hasCycle(head *ListNode) bool {
if head == nil {
return false
}
quick := head
slow := head
quick = head.Next
if quick != nil {
quick = head.Next
} else {
return false
}
for quick != nil && slow != nil {
if quick == slow {
return true
}
quick = quick.Next
if quick == nil {
return false
} else {
quick = quick.Next
}
slow = slow.Next
}
return false
}
160. Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins.
Example 1:
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output: Reference of the node with value = 8
Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
Example 2:
Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Reference of the node with value = 2
Input Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
Example 3:
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: null
Input Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
Notes:
If the two linked lists have no intersection at all, return null. The linked lists must retain their original structure after the function returns. You may assume there are no cycles anywhere in the entire linked structure. Each value on each linked list is in the range [1, 10^9]. Your code should preferably run in O(n) time and use only O(1) memory.
Solution
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func getIntersectionNode(headA, headB *ListNode) *ListNode {
if headA == nil || headB == nil {
return nil
}
l1 := 1
l2 := 1
d1 := headA
d2 := headB
for ;d1 !=nil;d1=d1.Next {
l1++
}
for ;d2 !=nil;d2=d2.Next {
l2++
}
diff := 0
if l1 > l2 {
diff = l1 - l2
for ;diff > 0; {
headA = headA.Next
diff -= 1
}
} else {
diff = l2 - l1
for ;diff >0; {
headB = headB.Next
diff -= 1
}
}
for headA != nil && headB != nil {
if headA == headB {
return headA
}
headA = headA.Next
headB = headB.Next
}
return nil
}
88. Merge Sorted Array
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
- The number of elements initialized in nums1 and nums2 are m and n respectively.
- You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2.
Example:
Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Constraints:
-10^9 <= nums1[i], nums2[i] <= 10^9nums1.length == m + nnums2.length == n
Solution:
func merge(nums1 []int, m int, nums2 []int, n int) {
/*反向思维,倒排*/
r := m + n - 1
l1 := m - 1
l2 := n - 1
for ;r >= 0 ; r-- {
if (l1 >= 0 && l2 >= 0 && nums1[l1] > nums2[l2]) || (l2 < 0) {
nums1[r] = nums1[l1]
l1--
} else {
nums1[r] = nums2[l2]
l2--
}
}
}
234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
Follow up: Could you do it in O(n) time and O(1) space?
Solution
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func isPalindrome(head *ListNode) bool {
slow := head
fast := head
for ; fast != nil; {
slow = slow.Next
fast = fast.Next
if fast != nil {
fast = fast.Next
}
}
// current slow in the middle
fast = head
slow = reverse(slow)
for slow.Next != nil {
if fast.Val != slow.Val{
return false
}
slow = slow.Next
fast = fast.Next
}
return true
}
func reverse(head *ListNode) *ListNode {
prev := new(ListNode)
for head != nil {
nextNode := head.Next
head.Next = prev
prev = head
head = nextNode
}
return prev
}
20. Valid Parentheses
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
Solution:
func isValid(s string) bool {
stack := []byte{}
for i := 0; i < len(s); i++ {
switch s[i] {
case '(', '[', '{':
stack = append(stack, s[i])
continue
case ')', ']', '}':
if len(stack) == 0 {
return false
}
ch := stack[len(stack)-1]
stack = stack[:len(stack)-1]
if (s[i] == ']' && ch != '[') || (s[i] == '}' && ch != '{') || (s[i] == ')' && ch != '(') {
return false
}
}
}
if len(stack) == 0{
return true
}
return false
}
172. Factorial Trailing Zeroes
Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
**Note: **
Your solution should be in logarithmic time complexity.
Solution:
func trailingZeroes(n int) int {
result := 0
f := 5
for f <= n {
result += n / f
f *= 5
}
return result
}
190. Reverse Bits
Reverse bits of a given 32 bits unsigned integer.
Example 1:
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:
Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
Note:
- Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
- In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above the input represents the signed integer -3 and the output represents the signed integer -1073741825.
Follow up:
If this function is called many times, how would you optimize it?
Solution
func reverseBits(num uint32) uint32 {
// divide & conquer
num = (num >> 16) | (num << 16)
num = ((num & 0xff00ff00) >> 8) | ((num & 0x00ff00ff) << 8)
num = ((num & 0xf0f0f0f0) >> 4) | ((num & 0x0f0f0f0f) << 4)
num = ((num & 0xcccccccc) >> 2) | ((num & 0x33333333) << 2)
num = ((num & 0xaaaaaaaa) >> 1) | ((num & 0x55555555) << 1)
return num
}
125. Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
Constraints:
sconsists only of printable ASCII characters.
Solution:
func isPalindrome(s string) bool {
s = strings.ToUpper(s)
var i, j int
i = 0
j = len(s)-1
for ; i < j; {
for ; (i < j) && !((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z')); {
i += 1
}
for ; (i < j) && !((s[j] >= '0' && s[j] <= '9') || (s[j] >= 'a' && s[j] <= 'z') || (s[j] >= 'A' && s[j] <= 'Z')); {
j -= 1
}
if (i < j && s[i] != s[j]) {
return false
}
i++
j--
}
return true
}
14. Longest Common Prefix
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
Example 1:
Input: ["flower","flow","flight"]
Output: "fl"
Example 2:
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
Solution:
func longestCommonPrefix(strs []string) string {
result := strings.Builder{}
if len(strs) == 0 {
return result.String()
}
for i := 0; i < len(strs[0]); i++ {
c := strs[0][i]
same := true
for _, s := range strs {
if i >= len(s) || s[i] != c {
same = false
break
}
}
if !same {
break
}
result.WriteByte(c)
}
return result.String()
}
7. Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Solution
import "math"
func reverse(x int) int {
ans := 0
for x != 0 {
last := x % 10
x /= 10
next := ans*10 + last
if (next-last)/10 != ans || next > math.MaxInt32 || next < math.MinInt32 {
return 0
}
ans = next
}
return ans
}
189. Rotate Array
Given an array, rotate the array to the right by k steps, where k is non-negative.
Follow up:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem. Could you do it in-place with O(1) extra space?
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Constraints:
- 1 <= nums.length <= 2 * 10^4
- It's guaranteed that nums[i] fits in a 32 bit-signed integer.
- k >= 0
Solution:
func rotate(nums []int, k int) {
k = k % len(nums)
result := append(nums[len(nums)-k:], nums[:len(nums)-k] ...)
// 必须这样赋值
for i := 0; i < len(nums); i++ {
nums[i] = result[i]
}
}
69. Sqrt(x)
Implement
int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4
Output: 2
Example 2:
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
Solution
func mySqrt(x int) int {
left := 0
right := x
for left <= right {
mid := (left + right) / 2
mul := mid * mid
if mul == x {
return mid
} else if mul < x {
left = mid + 1
} else {
right = mid - 1
}
}
return right
}