Lintcode1457 · Search Subarray go

/**
1457 · Search Subarray
Algorithms
Medium
Accepted Rate
40%

DescriptionSolutionNotesDiscussLeaderboard
Description
Given an array arr and a nonnegative integer k, you need to find a continuous array from this array so that the sum of this array is k. Output the length of this array. If there are multiple such substrings, return the one with the minimum ending position; if there are multiple answers, return the one with the minimum starting position. If no such subarray is found, -1 is returned.

The length of the array does not exceed 10^610
​6
​​ , each number in the array is less than or equal to 10^610
​6
​​ , and k does not exceed 10^610
​6
​​ .

Example
Example 1 :

Input:arr=[1,2,3,4,5] ,k=5
Output:2
Explanation:
In this array, the earliest contiguous substring is [2,3].
Example 2 :

Input:arr=[3,5,7,10,2] ,k=12
Output:2
Explanation:
In this array, the earliest consecutive concatenated substrings with a sum of 12 are [5,7].
Tags
Company
Amazon

https://blog.youkuaiyun.com/qq_46105170/article/details/111027683

https://www.lintcode.com/problem/1457/
*/

/**
 * @param arr: The array
 * @param k: the sum
 * @return: The length of the array
 */
func searchSubarray (arr []int, k int) int {
	// Write your code here
	for i := 1; i < len(arr); i++ {
		arr[i] += arr[i - 1]
	}
	var indexMap = make(map[int]int)
	for i := len(arr) - 1; i >= 0; i-- {
		indexMap[arr[i]] = i
	}
	indexMap[0] = -1
	for i := 0; i < len(arr); i++ {
		v, ok := indexMap[arr[i] - k]
		if ok && i > v {
			return i - v
		}
	}
	return -1
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值