您的位置 首页 编程语言

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.

美国面试题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;

    }
}

猫叔总结了 适合新手操作的副业 《淘宝虚拟产品月入2万的 6个 细分类目》的电子书 仅供参考

如果你对虚拟产品比较感兴趣,可以点击:

淘宝卖什么虚拟产品赚钱(月入2万+)

hadoopall

关于花猫大叔短视频创业 作者: hadoopall

热门文章

发表评论

电子邮件地址不会被公开。