arrays - What's the best way to count occurences of positive, negative, and 0 values in an unsorted array?
问题描述
The below works but how would I optimize this? I imagine looping through the array would become expensive as it grows. I could create a map of the original array to store the number of occurrences for each value and then check those values for +/-/0 in another loop but that's even worse.
package main
import (
"fmt"
)
func main() {
arr := []int{2, 5, 6, 7, 8, 2, 4, 1, 1, 1, 2, -2, -2, 2, 2, 3, -1, 0, 0, 0, 0, 2, 5, 4, 9, 8, 7, 2, -3, -7}
var p, n, z int = 0, 0, 0
for _, v := range arr {
if v > 0 {
p++
} else if v < 0 {
n++
} else if v == 0 {
z++
}
}
fmt.Println(p, n, z)
}
解决方案
如果你的输入结构是一个未排序的数组,那么 O(n) 是你能做的最好的,也就是说,遍历数组,比较每个元素一次。
如果可以的话,您可以使用两个数组和一个整数,一个数组用于负数,一个数组用于正数,以及一个整数来计算零的数量。然后,不再需要计数,您可以简单地获取数组的长度。
推荐阅读
- r - 带因子变量的回归
- c - 我做的,while循环没有按我的意思工作:((C语言)
- vb.net - 如何在 vb.net 中打印 listview 表?
- git - “go get”无法下载 go 包,托管在 Github Entreprise 上的 git 存储库(在 VPN 之后)
- java - 如何将带有 JSON 数组的字符串解析为变量,以便将它们放入 html 表中?
- javascript - 将 async await 与 try catch 结合使用的问题
- mysql - Spring Boot 无法自动创建数据库(使用 Jdbc + Mysql)
- javascript - TypeError:weeklyData.map 不是函数
- javascript - 使用 setState() 更新数组时出现 React / TypeScript 错误
- background - 是否可以使用 LaTeX 包“子文件”和“背景”?