源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

java求数组元素重复次数和java字符串比较大小示例

  • 时间:2020-10-29 07:24 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:java求数组元素重复次数和java字符串比较大小示例
[u]复制代码[/u] 代码如下:
/**  * Name: 求数组中元素重复次数对多的数和重复次数  * Description:  * 数组中的元素可能会重复,这个方法可以找出重复次数最多的数,同时可以返回重复了多少次。  * 但需要知道这个数组中最大的元素是多少,如果无法确定,就悲剧啦~  *  * @param array目标数组;  *           max数组中数据的最大值;  * @return 返回一个包含重复次数最多的数(value)和重复次数(maxCount)的map集合;  *                  内部出现异常,默认返回0;  * @throws  * @Author 杨元  */ public static Map<String, Integer> arraySearch(int[] array,int max){   //结果集合   Map<String, Integer> resultMap = new HashMap<String, Integer>();   //重复的次数   int maxCount = 0;   //重复次数对多的数   int value = 0;   try{     //初始化数据数组,用来存放每个元素出现的次数     int[] dataArray = new int[max+1];     //遍历要查找的数组,以每个元素为下标,直接定位数据数组,进行+1操作,表示出现了一次     for(int i : array){       dataArray[i]++;     }     //找到数据数组中最大值     for(int i=0;i<dataArray.length;i++){       if(dataArray[i]>maxCount){         maxCount=dataArray[i];         value=i;       }     }   }catch (Exception e) {}   resultMap.put("maxCount", maxCount);   resultMap.put("value", value);   return resultMap; } /**  * Name: 比较两个字符串大小  * Description: 比较的规则和数据库中的order by效果一致;  *                 null自动转为空,空字符串最大;  *  * @param first 要比较的第一个字符串;  *           second 要比较的第二个字符串;  * @return first大于second返回正数;  *            first等于second返回0;  *         first小于second返回负数;  *         内部异常默认返回0;  *         返回值非固定值哦~~;  * @throws  * @Author 杨元  */ public static int compareString(String first,String second){   int result = 0;   try{     //null转空     first = first==null?"":first;     second = second==null?"":second;     //预先记录字符串长度,避免反复读取     int firstLength=first.length();     int secondLength=second.length();     //处理含有空串的特殊情况     if("".equals(first) || "".equals(second)){       //谁长谁小       result = secondLength-firstLength;     }else{       //临时空间,用来存放ascii码总和       int firstCount = 0;       int secondCount = 0;       //用纯运算得出两个数中较小的数,实在是bt       int minLength = (secondLength*(firstLength/secondLength) + firstLength*(secondLength/firstLength))/(firstLength/secondLength + secondLength/firstLength);       //按两个字符串中较短的位数去逐位截取,防止越界       for(int i=0;i<minLength;i++){         //求ascii码和         firstCount+=first.substring(i,i+1).getBytes()[0];         secondCount+=second.substring(i,i+1).getBytes()[0];         //和不相等,说明已经比较出了大小         if(firstCount!=secondCount){           break;         }       }       if(firstCount==secondCount){         //长度长的大         result = firstLength-secondLength;       }else{         //总和大的大         result = firstCount-secondCount;       }     }   }catch (Exception e) {}   return result; }
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部