美国面试题12
1.题目:
An array is called centered-15 if some consecutive sequence of elements of the array sum to 15 and this sequence is preceded and followed by the same number of elements. For example
{3, 2, 10, 4, 1, 6, 9} is centered-15 because the sequence 10, 4, 1 sums to 15 and the sequence is preceded by two elements (3, 2) and followed by two elements(6,9).
Write a method called isCentered15 that returns 1 if its array argument is centered-15, otherwise it returns 0.
If you are programming in Java or C#, the function prototype is
int isCentered15(int[ ] a)
If you are programming in C++ or C, the function prototype is
int isCentered5(int a[ ], int len) where len is the number of elements in the array.
2. 测试样例
3. java实现代码:
public class Centered15 {
public static void main(String[] args) {
// int a[] = {3,2,10,4,1,6,9};
// int a[] = {2,10,4,1,6,9};
// int a[] = {3,2,10,4,1,6};
// int a[] = {1,1,8,3,1,1};
// int a[] = {9,15,6};
// int a[] = {1,1,2,2,1,1};
int a[] = {1,1,15,-1,-1};
System.out.println(isCentered15(a));
}
public static int isCentered15(int[] a){
int length = a.length;
if(length==0){
return 0;
}else if(length==3 && a[1]==15){
return 1;
}
int x =1;
while (x!=length-2) {
int sum = 0;
for (int i = x; i < length - 1; i++) {
sum = sum + a[i];
// System.out.println("x=" + x);
if (sum == 15) {
//记录 x,i, 判断是不是中间
System.out.println("i=" + i+"sum="+sum+"x="+x);
if(length-i-1 == x) {
return 1;
}
}
}
x ++;
}
return 0;
}
}