数组中前k个重复最多的字符串
题目详情:数组中前k个重复最多的字符串
给出一个数组,这个数组中有很多重复的字符串元素,请输出重复最多的前k个元素。
题目分解/做题思路
分解题目信息:
1.字符串数组,其中含有重复元素
2.输出重复最多的前k个元素
方法:
使用键值对存储 ,Key存储字符串,Value存储出现的次数
然后排序,打印输出前k个
解题方法
public static void main(String[] args) {
String[] strArr = {"abb","abb","abb","qwe","bb","bb"};
int k = 2;
resultArr(strArr, k);
}
public static void resultArr(String[] arr ,int k){
//首先使用HashMap存储Key、Value,value为出现得次数,key为字符串
Map<String,Integer> map = new HashMap<>();
//遍历数组,存入map
for (String arrnum: arr) {
//计数,value默认为0,出现过就+1
map.put(arrnum, map.getOrDefault(arrnum,0)+1);
}
//对map进行排序
List<Map.Entry<String,Integer>> entries = new ArrayList<>(map.entrySet());
entries.sort((a,b) -> b.getValue() - a.getValue());//从大到小排
//将前k个放入list
List<String> result = new ArrayList<>();
for (int i = 0; i < k; i++) {
result.add(entries.get(i).getKey());
}
//不想让打印出来的结果带[],直接使用join连接,每个字符串用,链接
String res = String.join(",",result);
System.out.println(res);
}
//输出结果:abb,qwe
类似题目2
题目详情:找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。
数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。
请找出数组中任意一个重复的数字。
题目分解/做题思路
分析题目要求:
1.给一个数组,其中有重复元素
2.随机打印出其中得重复得元素
解题思路:
1.使用Map存储数组中得元素和重复出现得次数
2、取出value>1得key
3、生成一个随机数,随机数得范围小于等于重复的元素的个数
解题方法
class Solution {
//题目的意思是随机打印一个重复的元素
public int findRepeatNumber(int[] nums) {
Map<Integer,Integer> map =new HashMap<>();
//将数组中得元素循环放入map中,并记录出现的次数
for (Integer numsA: nums) {
map.put(numsA,map.getOrDefault(numsA,0)+1);
}
//将map中得值存放List中,方便后面得排序、遍历取值
List<Map.Entry<Integer,Integer>> entries = new ArrayList<>(map.entrySet());
//排序,从小到大排
entries.sort((a,b)->a.getValue() - b.getValue());
List<Integer> res = new ArrayList<>();
//遍历list,打印出出现次数大于1得元素,然后放入res中
for (Map.Entry<Integer,Integer> entry: entries) {
if(entry.getValue() > 1){
res.add(entry.getKey());
}
}
//此时res中得元素都是具有重复数得元素,随机返回一个
Random random = new Random();
//生成随机数,随机数得范围 0 ~ res-1 【random.nextInt(n) 取值范围是 0 ~ n-1】
int randomNum = random.nextInt(res.size());
return res.get(randomNum);
}
}
类似题目3
题目详情:数组中出现次数超过一半的数字
数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
示例 1:
输入: [1, 2, 3, 2, 2, 2, 5, 4, 2]
输出: 2
题目分解/做题思路
分析题目要求:
1、有一个数组,其中有重复的数字
2、有一个数字出现次数 》 数组长度的一半
解题方法
class Solution {
public int majorityElement(int[] nums) {
int length = nums.length;
//数组->元素->出现的次数 ==> HashMap
Map<Integer,Integer> map = new HashMap<>();
//将数组放入map中
for ( int n: nums) {
map.put(n,map.getOrDefault(n,0)+1);
}
//将map放入list
List<Map.Entry> list = new ArrayList<>(map.entrySet());
//数组是非空的,如果只存在一个元素,直接返回他
int result =(int) list.get(0).getKey();
for (int i = 0; i < list.size(); i++) {
//取出次数大于数组长度一半的元素
if((int) list.get(i).getValue() > length/2){
result =(int) list.get(i).getKey();
}
}
return result;
}
}
相关标签:HashMapmap遍历