"Shortest Subarray with Sum at Least K" hard task No 862 solution using 2 queues, still failing by time complexity
This commit is contained in:
@@ -1,44 +1,81 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type Queue struct {
|
||||
front int
|
||||
rear int
|
||||
size int
|
||||
QArray [100000]int
|
||||
}
|
||||
|
||||
func (q *Queue) initQueue(size int) {
|
||||
q.size = size
|
||||
//q.QArray = [size]int{}
|
||||
q.front = -1
|
||||
q.rear = -1
|
||||
}
|
||||
|
||||
func (q *Queue) enqueue(value int) {
|
||||
if q.rear == q.size-1 {
|
||||
fmt.Println("Queue is Full")
|
||||
return
|
||||
} else {
|
||||
q.rear++
|
||||
q.QArray[q.rear] = value
|
||||
}
|
||||
}
|
||||
|
||||
func (q *Queue) dequeue() int {
|
||||
var x int = -1
|
||||
if q.front == q.rear {
|
||||
fmt.Println("Queue is Empty!")
|
||||
} else {
|
||||
q.front++
|
||||
x = q.QArray[q.front]
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
func (q *Queue) erase() {
|
||||
q.front = -1
|
||||
q.rear = -1
|
||||
}
|
||||
|
||||
func ShortestSubarray(nums []int, k int) int {
|
||||
if len(nums) == 0 {
|
||||
return -1
|
||||
}
|
||||
|
||||
sz := 999999
|
||||
sum := nums[0]
|
||||
carry := 1
|
||||
queue := &Queue{}
|
||||
queue2 := &Queue{}
|
||||
|
||||
for i := 0; i < len(nums)-1; i++ {
|
||||
if sum >= k {
|
||||
if (carry > 0) && (sz > carry) {
|
||||
sz = carry
|
||||
}
|
||||
}
|
||||
sum = nums[i]
|
||||
for j := i + 1; j < len(nums); j++ {
|
||||
if sum >= k {
|
||||
if sz > (j - i) {
|
||||
sz = j - i
|
||||
}
|
||||
break
|
||||
} else {
|
||||
sum += nums[j]
|
||||
carry = j - i + 1
|
||||
queue.initQueue(100000)
|
||||
queue2.initQueue(100000)
|
||||
|
||||
for i, n := range nums {
|
||||
if i < len(nums) {
|
||||
queue.enqueue(n)
|
||||
}
|
||||
if n >= k {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
for wndSz := 2; wndSz <= len(nums); wndSz++ {
|
||||
for i := wndSz - 1; i < len(nums); i++ {
|
||||
el := queue.dequeue()
|
||||
s := el + nums[i]
|
||||
queue2.enqueue(s)
|
||||
if s >= k {
|
||||
return wndSz
|
||||
}
|
||||
}
|
||||
t := queue
|
||||
queue = queue2
|
||||
queue2 = t
|
||||
queue2.erase()
|
||||
}
|
||||
|
||||
if sz == 999999 {
|
||||
if sum >= k {
|
||||
return carry
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
if (sum >= k) && (carry > 0) && (carry < sz) {
|
||||
return carry
|
||||
}
|
||||
|
||||
return sz
|
||||
return -1
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user