Given an array of integers and a number x, find the smallest subarray with sum greater than the given value.
input: a = {1,4,45,6,0,19}
x = 510
output: 3
input: a1 = {1,10,5,2,7}
x1 = 9
output:1
intput: a2= {1,11,100,1,0,200,3,2,1,250}
x2 = 280
output: 4
设置start和end指针,从数组第一个元素开始累加,累加后与x值进行比较,若大于x,则从队列尾端减去一个值后再做比较,如果小于x则继续往后累加。当end指针大于数组长度时,报错,没有正确答案。每次获得大于x的值时,都与当前存下的长度值做比较,如果小于则替换。
package p_3;
public class Main {
public static void main(String args[])
{
int[] a = {1,4,45,6,0,19};
int x = 510;
int number = a.length;
int[] a1 = {1,10,5,2,7};
int x1 = 9;
int number1 = a1.length;
int[] a2= {1,11,100,1,0,200,3,2,1,250};
int x2 = 280;
int number2 = a2.length;
int xxx = sum(a,x,number);
if(xxx == -100)
{
System.out.println("No possilbe");
}
else
{
System.out.println(xxx);
}
xxx = sum(a1,x1,number1);
if(xxx == -100)
{
System.out.println("No possilbe");
}
else
{
System.out.println(xxx);
}
xxx = sum(a2,x2,number2);
if(xxx == -100)
{
System.out.println("No possilbe");
}
else
{
System.out.println(xxx);
}
}
public static int sum(int[] a,int x,int number)
{
int current_number = 999;
int start = 0;
int end = 1;
int total = a[0];
while(end<number)
{
if(total<=x)
{
total = total+a[end];
end++;
}else{
int temp_number = end - start;
if(temp_number<current_number)
{
current_number = temp_number;
}
total = total - a[start];
start ++;
}
}
if(current_number == 999)
return -100;
else
return current_number;
}
}