您的位置 首页 编程语言

Define an array to be a 121 array if all its elements are either

美国程序员面试题

 

Define an array to be a 121 array if all its elements are either 1 or 2 and it begins with one or more 1s followed by a one or more 2s and then ends with the same number of 1s that it begins with. Write a method named is121Array that returns 1 if its array argument is a 121 array, otherwise, it returns 0.

 

If you are programming in Java or C#, the function signature is
int is121Array(int[ ] a)
If you are programming in C or C++, the function signature is
int is121Array(int a[ ], int len) where len is the number of elements in the array a.

 

测试样例

 

 

java实现代码:

package com.zzy;

/**
 * 更多请关注: http://huamaodashu .com
 * Created by huamaodashu on 23/07/2018.
 */
public class is121Array {


    public static void main(String[] args) {

//        int [] a={1, 2, 1};
//        int [] a={1, 1, 2, 2, 2, 1, 1};
//        int [] a={1, 1, 2, 2, 2, 1, 1, 1};
//        int [] a={1, 1, 2, 1, 2, 1, 1};
//        int [] a={1, 1, 1, 2, 2, 2, 1, 1, 1, 3};
//        int [] a={1, 1, 1, 1, 1, 1};
//        int [] a={2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1};
//        int [] a={1, 1, 1, 2, 2, 2, 1, 1, 2, 2};
        int [] a={2, 2, 2};
        System.out.println(is121Array(a));
//        System.out.println(a.length);

    }
    public static int is121Array(int[]a){

        if(a.length >= 3 && a[0]==1){
            if(a[a.length/2]!=2){
                return 0;
            }
            for (int i = 0; i < a.length; i++) {

                if(a[i]!=a[a.length-1-i]){
                    return 0;
                }
            }
            return 1;
        }
        return 0;

    }
}

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

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

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

hadoopall

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

热门文章