Skip to content

第四周作业_006 #274

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.DS_Store
.idea
8 changes: 0 additions & 8 deletions .idea/algorithm.iml

This file was deleted.

6 changes: 0 additions & 6 deletions .idea/misc.xml

This file was deleted.

8 changes: 0 additions & 8 deletions .idea/modules.xml

This file was deleted.

6 changes: 0 additions & 6 deletions .idea/vcs.xml

This file was deleted.

227 changes: 0 additions & 227 deletions .idea/workspace.xml

This file was deleted.

33 changes: 33 additions & 0 deletions Week_04/id_6/LeetCode_053_6.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package main

import "fmt"

/**
时间复杂度:O(n)
空间复杂度:O(1)
*/
func maxSubArray(nums []int) int {
answer := nums[0]
sum := 0
for _, v := range nums{
if sum > 0 {
sum += v
}else {
// 如果 sum 小于 0 那还不如从当前位置开始计算
sum = v
}
answer = maxInt(sum, answer)
}
return answer
}

func maxInt(a int, b int) int {
if a > b {
return a
}
return b
}

func main() {
fmt.Println("结果是:", maxSubArray([]int{-2,1,-3,4,-1,2,1,-5,4}))
}
80 changes: 80 additions & 0 deletions Week_04/id_6/LeetCode_169_6.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package main

import "fmt"

/**
暴力法
时间复杂度:O(n^2)
空间复杂度:O(1)
*/
func majorityElement(nums []int) int {
majorityCount := len(nums)/2
for _, v := range nums {
count := 0
for _, num := range nums {
if v == num {
count++
}
}
if count > majorityCount {
return v
}
}
return -1
}

/**
哈希表
时间复杂度:O(n)
空间复杂度:O(n)
*/
func majorityElement1(nums []int) int {
majorityCount := len(nums)/2
m := make(map[int]int, len(nums))
for _, num := range nums {
if _, ok := m[num]; ok {
m[num]++
}else {
m[num] = 1
}
}
for k := range m {
if m[k] > majorityCount {
return k
}
}
return -1
}

/**
Boyer-Moore 投票算法 (当不存在众数的时候此方法不适合)
时间复杂度:O(n)
空间复杂度:O(1)
*/
func majorityElement2(nums []int) int {
count := 0
var candidate int

for _, num := range nums {
if count == 0 {
candidate = num
}
if num == candidate {
count += 1
}else {
count -= 1
}
}
return candidate
}

func main() {
nums := []int{3,2,3}
fmt.Println("结果是:", majorityElement(nums))

nums1 := []int{3,2,3}
fmt.Println("结果是:", majorityElement1(nums1))

nums2 := []int{3,2,3}
fmt.Println("结果是:", majorityElement2(nums2))
}
Loading