国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

java求數組元素重復次數和java字符串比較大小示例

2019-11-26 15:30:49
字體:
來源:轉載
供稿:網友

復制代碼 代碼如下:

/**
 * 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;
}

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 剑川县| 筠连县| 固安县| 天镇县| 合阳县| 柳林县| 沙田区| 哈尔滨市| 富平县| 雷波县| 搜索| 杂多县| 神农架林区| 宝兴县| 五常市| 清原| 南木林县| 封开县| 大厂| 万载县| 平昌县| 榕江县| 房山区| 敦煌市| 和林格尔县| 长海县| 林甸县| 磴口县| 繁昌县| 资兴市| 郯城县| 彭泽县| 巩留县| 兴业县| 北宁市| 泸溪县| 楚雄市| 台中县| 石林| 惠东县| 勃利县|