日常题

No1

  求最大公共子字符串

 public static String maxSubstring(String strOne, String strTwo){
        // 参数检查
        if(strOne==null || strTwo == null){
            return null;
        }
        if(strOne.equals("") || strTwo.equals("")){
            return null;
        }
        // 二者中较长的字符串
        String max = "";
        // 二者中较短的字符串
        String min = "";
        if(strOne.length() < strTwo.length()){
            max = strTwo;
            min = strOne;
        } else{
            max = strTwo;
            min = strOne;
        }
        String current = "";
        // 遍历较短的字符串,并依次减少短字符串的字符数量,判断长字符是否包含该子串
        for(int i=0; i<min.length(); i++){//  如 abcdd  和 bcaa            先扣住end部分的字符,然后一个for循环看begin从0~end是否有符合的最大串,
            for(int begin=0, end=min.length()-i; end<=min.length(); begin++, end++){
                current = min.substring(begin, end);
                if(max.contains(current)){
                    return current;
                }
            }
        }
        return null;
    }

 NO2 找出数组中出现次数超过一半的数(时间复杂度O(n))

 

方法一:每次取出两个不同的数,剩下的数字中重复出现的数字肯定比其他数字多,将规模缩小化。如果每次删除两个不同的数(不管包括不包括最高频数),那么在剩余的数字里,原最高频数出现的频率一样超过了50%不断重复这个过程,最后剩下的将全是同样的数字,即最高频数。此算法避免了排序,时间复杂度只有O(n),空间复杂度为O(1)。

 public  static int maxChanceNum(int []a){
        int findNum=0;
        int count=0;
        for(int i=0;i<a.length;i++){
            if(count ==0){
                findNum=a[i];
                count=1;
            }else{
                if(findNum==a[i]){
                    count++;
                }else{
                    count--;
                }

            }
        }

        return  findNum;
    }

  方法二:hashmap     用hashmap key存数组中的元素,value存出现的次数  

 public  static int maxChanceNum(int []a){

        Map<Integer,Integer> map=new HashMap<Integer,Integer>();
       for(int i=0;i<a.length;i++){
           if(map.containsKey(a[i])){
               map.put(a[i],map.get(a[i])+1);
           }else{
               map.put(a[i],1);
           }
       }
        int findNum=map.get(a[0]);
        for(int i=0;i<map.size();i++){
           if(map.get(a[i])>findNum){
               findNum=map.get(a[i]);
           }
        }
        return  findNum;
    }

  

No3

  一个公司有一个职员 然后三个月考察期满就可以推荐一个新职员。考察期满的职员每个月会推荐一个新的职员。新职员还需要三个月考察期。

 

 public static int Count(int n){//列出count值  找规律    索引 2+4=5 索引 3+5=6.。。。
        int count=1;
        if(n<=3){
            count=1;
        }
        if(n==4){
            count=2;
        }
        if(n>4){
            count=Count(n-1)+Count(n-3);
        }

        return count;
    }

 

 No4

   

 

posted @ 2017-09-06 10:44  不会就问咯  阅读(319)  评论(0编辑  收藏  举报