# Leetcode nearest and sub-arrays

Source: Internet
Author: User

This is Lintcode's title: http://www.lintcode.com/zh-cn/problem/subarray-sum-closest/

Give an array and K, find a sub-array, and nearest k, if there are multiple returns to any one.

Of course n squared can be solved, but extra space can be onlogn.

The idea is to use the S (i)-S (j) approach.

First calculate all the S (i), then deposit Map,key is the position of the last element Sum,value.

Then the sum is sorted, and then the sum is traversed once, it is only necessary to determine the two sum of sums before and after the only difference can be found closest to K.

Here's The Go code:

```Package main

Import (
"FMT"
"Sort"
)

type P struct{
sum, index int
}

type PList []*p

func (List PList) len () int{
return len (list)
}

func (list PList) less (i, J int) bool{
return list [I].sum < List[j].sum
}

func (list PList) Swap (i, J int) {
list[i], list[j] = List[j], list[i]
}
func ABS (x int) int{
if x >= 0{
return x
}
return-x
}

func subarraysum (Nums []int, K int) (int, int) {
sum: = 0
list: = plist{}
P: = new (p)
p.sum = 0
p.index = 1
list=append (l IST, p) for
i,v: = range nums{
sum + = v
p: = new (p)
p.sum = sum
p.index = i
list=append (list , p)
}
sort. Sort (list)
min, F, b:= 1000000, 0, 0 for
i,v: = Range list{
If i==0 {
continue
}
cur: = ABS ( V.SUM-LIST[I-1].SUM-K)
If cur < min{
min = cur
f = list[i-1].index-1
B = List[i].index
}
}
Return f,b
}

func main () {
array: = []int{-3, 1, 1, -3, 5}
K: = 0
F, b: = Subarraysum (array, k)
fmt. Println (f, b)
}
```

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.