美国程序员面试题:
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;
}
}