加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:13:36 所属栏目:Java 来源:网络整理
导读:复制代码 代码如下: /** * Name: 求数组中元素重复次数对多的数和重复次数 * Description: * 数组中的元素可能会重复,这个方法可以找出重复次数最多的数,同时可以返回重复了多少次。 * 但需要知道这个数组中最大的元素是多少,如果无法确定,就悲剧啦~ * *

复制代码 代码如下:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读