Java查找数组重复元素,并打印重复元素、重复次数、重复元素位置

原博地址:http://www.cnblogs.com/lanrumeng/p/9814088.html

做分班系统时要满足一个需求:名字读音相同的同学尽量不在一个班。自己想了半个多小时没想出来,找了个Java的,我先学习学习试试。

package sort;

import org.testng.annotations.Test;
import sun.org.mozilla.javascript.internal.ast.NewExpression;

import java.util.*;

/**
 * Created by liangwei on 2018/10/18.
 */
public class SearchString {
    /**
     * 找出重复字符、记录重复字符次数、记录重复字符位置
     * @param str
     * @return map
     */
    public Map get_str_count_index(String[] str){
        Map<String,Map<Integer,ArrayList>> map = new HashMap<String ,Map<Integer,ArrayList>>();//key值记录重复的字符串,value记录出现的次数和位置
        int i = 0;
        for (String s:str ){
            if (map.get(s)==null){
                Map<Integer,ArrayList> count_where = new HashMap<Integer ,ArrayList>();//key值记录重复字符串出现的次数,value记录重复字符出现的位置
                int count = 1;//重复字符串计数器
                ArrayList<Integer> list = new ArrayList<Integer>();
                list.add(i);//重复字符串下标
                count_where.put(count,list);
                map.put(s,count_where);
                i++;
            }else {
                for (int c:map.get(s).keySet()){
                    ArrayList index = map.get(s).get(c);
                    index.add(i);//增加出现index位置
                    c++;
                    map.get(s).put(c,index);//更新计数器和下标信息
                    map.get(s).remove(--c);//删除掉之前的记录信息
                }
                i++;
            }
        }
        return map;
    }

    public void display(String[] arry) throws Exception{
        if (arry==null){
            throw new Exception("输入数组为空,请重新输入");
        }
        Map<String,HashMap<Integer,ArrayList>> map = get_str_count_index(arry);
        ArrayList count = new ArrayList<Integer>();//存取所有字符串出现的次数
        for (Map.Entry<String,HashMap<Integer,ArrayList>> key : map.entrySet()){//循环获取记录字符串重复次数和位置map
            for (Map.Entry<Integer,ArrayList> map1 :key.getValue().entrySet()){//循环获取记录字符串重复次数
                count.add(map1.getKey());
            }
        }
       // Arrays.sort(count.toArray());
        Collections.sort(count);//对集合排序,默认是升序,最后一个是重复次数最多的
        //打印重复次数最多的元素信息
        for (String key : map.keySet()){//循环获取所有的重复字符串
            for (int c:map.get(key).keySet()){//循环获取重复字符串的次数
                if (c == count.get(count.size()-1)){//和最大重复次数对比,相等就代表当前的字符串是重复次数最多的那个
                    System.out.printf("重复次数最多的字符串是:%s,重复次数%d,所在位置:%s\n",key,c,map.get(key).get(c));
                }
            }
        }
        //输出指定重复次数的字符串信息
        for (String key :map.keySet()){
            for (int c:map.get(key).keySet()){
                if (c==5||c==6||c==1){
                    System.out.printf("重复字符串:%s,重复次数:%d,重复字符串出现位置:%s\n",key,c,map.get(key).get(c));
                }
            }
        }
    }

    public static void main(String[] args) {
        String[] arry = {"aa","bb","cc","bb","aa","ooo","dd","aaa","aa"};
       // String[] arry = {};
        SearchString searchString = new SearchString();
        try {
            searchString.display(arry);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用线性查找和二分查找两种方法来查找数组中元素。 线性查找是逐个遍历数组元素,直到找到目标元素或遍历完整个数组。如果找到目标元素,返回该元素数组中索引;如果遍历完整个数组仍未找到目标元素,则返回-1。示例代码如下: ``` public static int getIndex(int[] arr, int key) { for (int i = 0; i < arr.length; i++) { if (arr[i == key) { return i; // 查找到该元素返回该元素数组中索引 } } return -1; // 没有查找到该元素返回-1 } ``` 二分查找是一种更高效的查找算法,但要求数组必须有序。它通过将数组分成两部分,并比较目标元素与中间元素的大小来确定目标元素位置。如果找到目标元素,返回该元素数组中索引;如果未找到目标元素,则返回"-插入点"。插入点指的是在数组中将目标元素插入的位置,即范围内第一个大于目标元素元素索引。示例代码如下: ``` import java.util.Arrays; public class FindArray { public static void main(String[] args) { double[] score = {99.5, 100, 98, 97.5, 110, 95, 85.5, 100}; Arrays.sort(score); // 对数组进行排序 int index1 = Arrays.binarySearch(score, 100); // 查找100的位置 int index2 = Arrays.binarySearch(score, 60); // 查找60的位置 System.out.println("查找到100的位置是:" + index1); System.out.println("查找到60的位置是:" + index2); } } ``` 在以上示例中,我们先使用`Arrays.sort()`方法对数组进行排序,然后使用`Arrays.binarySearch()`方法进行二分查找。当找到目标元素时,返回其在数组中索引;否则返回"-插入点"。 希望以上解答能满足您的需求,如果还有其他问题,请随时提问。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [JAVA--数组元素查找方法](https://blog.csdn.net/Xin6Yang/article/details/88778033)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Java 数组查找指定元素](https://blog.csdn.net/weixin_52899638/article/details/124508080)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值