您的位置 首页 编程语言

Define an array to be packed if all its values are positive, each value n appears n times and all equal values are in consecutive locations.

美国面试题

 

Define an array to be packed if all its values are positive, each value n appears n times and all equal values are in consecutive locations. So for example, {2, 2, 3, 3, 3} is packed because 2 appears twice and 3 appears three times. But {2, 3, 2, 3, 3} is not packed because the 2s are not in consecutive locations. And {2, 2, 2, 3, 3, 3} is not packed because 2 appears three times.
Write a method named isPacked that returns 1 if its array argument is packed, otherwise it returns 0. You may assume that the array is not null
If you are programming in Java or C#, the function signature is int isPacked(int[ ] a)
If you are programming in C++ or C, the function signature is int isPacked(int a[ ], int len) where len is the length of the array.

 

测试样例:

 

 

 

java代码实现:

package com.zzy;

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

    public static void main(String[] args) {

//        int [] a={2, 2, 1};
//        int [] a={2, 2, 1, 2, 2};
//        int [] a={4, 4, 4, 4, 1,2, 2, 3, 3, 3};
//        int [] a={7, 7, 7, 7, 7,  7, 7, 1};
//        int [] a={7, 7, 7, 7, 1,  7, 7, 7};
//        int [] a={7, 7, 7, 7, 7,  7, 7};
        int [] a={};

        System.out.println(isPacked(a));

    }

    public static int isPacked(int[] a){
        if(a.length>0){
            int tmp=a[0];
            int count=1;

            for (int i = 1; i < a.length; i++) {
                if(tmp==a[i]){
                    count++;
                    int countgroup=0;
                    for (int j = 0; j < a.length; j++) {
                        if(a[j]==tmp){
                            countgroup++;
                        }
                    }
                    if(tmp!=countgroup){
                        return 0;
                    }
                }else { //不等于了,


                    if(tmp!=count){
                        System.out.println("ai="+i+"count="+count);
                        return 0;
                    }
                    tmp=a[i];
                    count=1;

                }
            }



            return 1;
        }
        return 1;
    }
}

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

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

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

hadoopall

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

热门文章

发表评论

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