Skip to content

Latest commit

 

History

History
110 lines (79 loc) · 4.06 KB

arts-0001.md

File metadata and controls

110 lines (79 loc) · 4.06 KB

1.Algorithm

[278]  First Bad Version

Easy    Binary Search

You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.

Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad.

You are given an API bool isBadVersion(version) which will return whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.

Example:

Given n = 5, and version = 4 is the first bad version.

call isBadVersion(3) -> false
call isBadVersion(5) -> true
call isBadVersion(4) -> true
Then 4 is the first bad version.

解答 本题可以采用常规的方法和基于二分查找的算法

(1).直接遍历查找,时间复杂度 O(n)
func firstBadVersion1(n int) int {
	for i := 1; i <= n; i++ {
		if isBadVersion(i) {
			return i
		}
	}
	return -1
}
(2).采用二分查找,时间复杂度 O(log(n))

说明:题目中确认有错误版本,因此最后返回的结束点是 low==high, 并且 isBadVersion(low)肯定是返回 true 的

func firstBadVersion2(n int) int {
	low, high := 1, n
	for low < high {
		mid := low + (high-low)/2
		isMidBad := isBadVersion(mid)
		if isMidBad {
			high = mid
		} else {
			low = mid + 1
		}
	}
	return low // 因为题目中确认有错误版本,因此直接返回low, low=high
}

2.Review

Go at Google: Language Design in the Service of Software Engineering

这篇文章整理自Rob Pike在SPLASH 2012的主题演讲修改后撰写的。主要讲述了Google开发新语言Go的原因以及Go的一些特性。【有些内容需要再次多读下】

2.1 Pain points

  • slow builds
  • uncontrolled dependencies
  • each programmer using a different subset of the language
  • poor program understanding (code hard to read, poorly documented, and so on)
  • duplication of effort
  • cost of updates
  • version skew
  • difficulty of writing automatic tools
  • cross-language builds

2.1 Go 特性

  • Clear dependencies
  • Clear syntax
  • Clear semantics
  • Composition over inheritance
  • Simplicity provided by the programming model (garbage collection, concurrency)
  • Easy tooling (the go tool, gofmt, godoc, gofix)

3.Tip

这周分享本周上线过程中的两个问题,想强调 checklist 的重要性

  • 1.生产环境与测试环境配置文件不一致问题
  • 2.测试环境中的测试代码发布到生产环境

第 1 个问题:因为对部分代码进行了重构,调整了配置参数的值,而只是调整了测试环境中的相应值,而忽略了生产配置文件相应的调整(因为没有预发环境,只能上到生产环境才能验证生产配置的有效性)

第 2 个问题:有个客户的个性化原因,把我们测试环境接口当成生产来调用,而我们接口输出给对方是需要计费的,但是测试环境上的调用不算次数。因此就对接口进行了简单的日调用次数限制。因为在测试环境上对某些接口了做了日调用限制,而上线时忘记了进行检查,将接口限制同步到了生产环境

总结:上线前要进行 checklist 检查,最好能有多人进行复查,避免疏忽遗漏。对于个性化需求,需要考虑情况,而不是临时的解决方案,考虑在不同条件,不同环境下的使用。

4.Share

分享一篇耗子大叔有关刷 leetcode 的文章:LEETCODE 编程训练 刷 leetcode 的好处:

  • 可以应付大公司的算法面试题(如果需要面试的话)
  • 锻炼自己的算法和编程能力

最近我也在刷 leetcode,初步定为每天刷 2 题,用 Go 语言刷,一方面可以更深入对 Go 语言的了解,同时能加强自己对算法的了解。