栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

复制代码 代码如下:

public static Map arraySearch(int[] array,int max){
  //结果集合
  Map resultMap = new HashMap();
  //重复的次数
  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      if(dataArray[i]>maxCount){
        maxCount=dataArray[i];
        value=i;
      }
    }
  }catch (Exception e) {}

  resultMap.put("maxCount", maxCount);
  resultMap.put("value", value);

  return resultMap;
}


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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/152210.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号