您的位置 首页 编程语言

isOnionArray

美国程序员面试题:

An onion array is an array that satisfies the following condition for all values of j and k:
if j>=0 and k>=0 and j+k=length of array and j!=k then a[j]+a[k] <= 10
Write a function named isOnionArray that returns 1 if its array argument is an onion array and returns 0 if it is not.
Your solution must not use a nested loop (i.e., a loop executed from inside another loop). Furthermore, once you determine that the array is not an onion array your function must return 0; no wasted loops cycles please!
If you are programming in Java or C#, the function signature is
int isOnionArray(int[ ] a)
If you are programming in C or C++, the function signature is
int isOnionArray(int a[ ], int len) where len is the number of elements in the array a.

 

 

2. 测试样例

 

 

3. java 实现

package com.zzy;

/**
 * 更多请关注: http://huamaodashu .com
 * Created by huamaodashu on 06/08/2018.
 */
public class OnionArray {
    public static void main(String[] args) {
//        int[]a = {1, 2, 19, 4, 5};
//        int[]a = {1, 2, 3, 4, 15};
//        int[]a = {1, 3, 9, 8};
//        int[]a = {2};
//        int[]a = {};
        int[]a = {-2, 5, 0, 5, 12};
        System.out.println(isOnionArray(a));

    }
    public static int isOnionArray(int[] a){
        int i=0;
        int k = 0;

        for (; i < a.length; i++) {
            k = a.length-1 - i;
            if(i!=k){
                if(a[i] + a[k]>10){
                    return 0;
                }
            }
        }
        return 1;

    }
}

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

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

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

hadoopall

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

热门文章

发表评论

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