Smallest Subarray with a given sum (easy)

刷题参考:https://blog.csdn.net/IBelieve2016/article/details/104544763 

#include<iostream>
#include<vector>
#include <unordered_map>
using namespace std;
/*
Given an unsorted array of nonnegative integers, find a continous subarray which adds to a given number. 

Examples:

Input: arr[] = {1, 4, 20, 3, 10, 5}, sum = 33
Ouptut: Sum found between indexes 2 and 4

Input: arr[] = {1, 4, 0, 0, 3, 10, 5}, sum = 7
Ouptut: Sum found between indexes 1 and 4

Input: arr[] = {1, 4}, sum = 0
Output: No subarray found
*/
int solution(vector<int> nums,int k){
	int res=0;
	int s=0;
	bool flag=false;
	unordered_map<int,int> smap;
	for(int i=0;i<nums.size();i++){
		s+=nums[i];
		//纪录第一个等于k的值的位置,它是最小值 
		if(s==k&&!flag){
			flag=true;
			res=i+1;
		}else if(smap.count(s-k)!=0){
			//如果前面的序列和 存在刚好等于s-k的值,那么就可以得到中间一个序列长 
			//比较当前最短和存在的序列最短,取最短的序列长 
			res=min(res,i-smap[s-k]);
		}
		if(smap.count(s)==0){
			smap[s]=i;
		}
	}
	return res; 
}
int main(){
	vector<int> nums {2,-1,2};
	cout<<solution(nums,3); 
	return 0;
} 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Jonathan is fighting against DIO's Vampire minions. There are n of them with strengths a1,a2,…,an. Denote (l,r) as the group consisting of the vampires with indices from l to r. Jonathan realizes that the strength of any such group is in its weakest link, that is, the bitwise AND. More formally, the strength level of the group (l,r) is defined as f(l,r)=al&al+1&al+2&…&ar. Here, & denotes the bitwise AND operation. Because Jonathan would like to defeat the vampire minions fast, he will divide the vampires into contiguous groups, such that each vampire is in exactly one group, and the sum of strengths of the groups is minimized. Among all ways to divide the vampires, he would like to find the way with the maximum number of groups. Given the strengths of each of the n vampires, find the maximum number of groups among all possible ways to divide the vampires with the smallest sum of strengths. Input The first line contains a single integer t (1≤t≤104) — the number of test cases. The description of test cases follows. The first line of each test case contains a single integer n (1≤n≤2⋅105) — the number of vampires. The second line of each test case contains n integers a1,a2,…,an (0≤ai≤109) — the individual strength of each vampire. The sum of n over all test cases does not exceed 2⋅105. Output For each test case, output a single integer — the maximum number of groups among all possible ways to divide the vampires with the smallest sum of strengths.c++实现
最新发布
07-07
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值