Leetcode 215 First K Largest Element

这种前几大的题通通用partition就可以在O(N)时间内解决,之所以要特意写个题解是因为想把partition的算法记下来,每次写都写得很纠结

程序看着比较奇怪,因为我是找的前k大,然后再找前k大里面最小的,之所以这样是为了复用之前
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/
的函数

type pair struct {
v int
p int
}

func maxProfit(k int, prices []int) int {
n := len(prices)
stack := make([]pair, n)
profits := make([]int, 0, n)
v := 0
p := -1
top := 0
for true {
for v = p + 1; v+1 < n && prices[v] >= prices[v+1]; v++ {
}
for p = v; p+1 < n && prices[p] <= prices[p+1]; p++ {
}
//fmt.Println(v,p)
if v == p {
break
}
/*case 1, do nothing but pop the last vp pair and put them into the profit array
/
for top > 0 && prices[v] <= prices[stack[top-1].v] {
profits = append(profits, prices[stack[top-1].p]-prices[stack[top-1].v])
top--
}
/
case 2, merge the two vp pairs
*/
for top > 0 && prices[p] >= prices[stack[top-1].p] {
profits = append(profits, prices[stack[top-1].p]-prices[v])
v = stack[top-1].v
top--
}
stack[top] = pair{v: v, p: p}
top++
}
for top > 0 {
profits = append(profits, prices[stack[top-1].p]-prices[stack[top-1].v])
top--
}
ans := 0
//fmt.Println(profits)
if len(profits) <= k {
ans = accumulate(profits)
return ans
}
ans = accumulate(firstKLargest(profits, k))
return ans

}

func accumulate(arr []int) int{
n := len(arr)
ans := 0
for i := 0; i < n; i++ {
ans += arr[i]
}
return ans
}

func firstKLargest(slice []int, k int) []int {
length := len(slice)

if length <= k {
    return slice
}

m := slice[rand.Intn(length)]

less := make([]int, 0, length)
more := make([]int, 0, length)
equal := make([]int, 0, length)

for _, item := range slice {
    switch {
    case item < m:
        less = append(less, item)
    case item > m:
        more = append(more, item)
    default :
        equal = append(equal, item)
    }
}
if len(more) > k {
    return firstKLargest(more, k)
} else if len(more) == k {
    return more
}else if len(more) + len(equal) >= k{
    more = append(more, equal[:k-len(more)]...)
    //fmt.Println("debug more",more)
    return more
}
more = append(more, equal...)
// fmt.Println("Less", less)
// fmt.Println("More", more)
// fmt.Println("Equal", equal)
part := firstKLargest(less, k-len(more))
return append(part, more...)

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,357评论 0 33
  • Lesson 11excuse[ik'skju:z] v.原谅2me[mi:,mi] pron.我(宾格)3yes...
    造物家英语阅读 5,286评论 0 0
  • 随着地球的自转,太阳照常从东方升起,今天早上的阳光仿佛一改往日的激烈,把温和而浪漫的阳光洒进了房间,昨天和...
    茶古马阅读 1,697评论 0 0
  • 我刚吃饭回来就看到他和他的不知所措。他站在前台,在陌生的环境里显得格格不入。 中等身材,剃着平头,浓眉,标准的国字...
    莎樂阅读 5,164评论 0 7
  • 我坐在一把藤木椅上,桌前放了一盆红色郁金香网丝花,一如当年制作时的鲜艳。我一时兴起铺开素描纸,想画起昨天梦...
    清天一梦阅读 2,854评论 0 3

友情链接更多精彩内容