当前位置: 移动技术网 > IT编程>开发语言>Java > java求数组元素重复次数和java字符串比较大小示例

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

2019年07月22日  | 移动技术网IT编程  | 我要评论
复制代码 代码如下:/** * 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;
}

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网