您的位置 首页 编程语言

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;

    }
}

 

花猫大叔总结了2020年抖音变现玩赚指南-进阶版的电子书 免费获取

链接: https://pan.baidu.com/s/1S7lF9AQAX2pdESlhF9Rl8Q

提取码:u8yv

 

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

热门文章

发表评论

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