复习:
1.Java中对象得到比较相关的三种方法
Object.equals | 相等还是不相等 |
Comparable.compareTo | 比较(内部比较,自然顺序) |
Comparator.compare | 比较(外部比较,基于比较器) |
2.如何定义一个泛型类
3.使用泛型:通配符,谁是谁的子类
新课:
1.搜索
1.1搜索中的模型
(1)纯Key模型:复杂度较小
(2)Key-Value模型:复杂度较大
2.Map的使用
1. Map中的Key不允许重复
2.Map可以直接打印,内部覆写了toString 方法
Ieratable(迭代器)
迭代器 —— Collection 接口
Map 接口—— 集合
3.元素类型
1.泛型 <两个类型变量>
Map.Entry<Integer,Integer> // <K的类型,V的类型>
2.静态内部类 Map.Entry
public class Map{
public static calss Entry{
}
}
//在外部使用静态内部类的语法:Map.Entry
4.练习题
1.找非空数组中只出现一次的数字
思路:数字和数字出现次数之间的映射关系
public class P4 {
public static class StringComparator implements Comparator<String>{
@Override
public int compare(String o1,String o2){
return o1.compareTo(o2);
}
}
//统计单词出现的次数
Map<String,Integer>count(String[] words){
Map<String,Integer> wordToCount = new HashMap<>();
for(String word:words){
int c = wordToCount.getOrDefault(word,0);
wordToCount.put(word,c+1);
}
return wordToCount;
}
//每个次数 ——>那些单词
private static Map<Integer,List<String>> remap(Map<String,Integer>wordToCount){
Map<Integer,List<String>> countToWordList = new HashMap<>();
for(Map.Entry<String,Integer> e:wordToCount.entrySet()){
String word = e.getKey();
int count = e.getValue();
List<String> wordList = countToWordList.get(count);
if(wordList == null){
wordList = new ArrayList<>();
countToWordList.put(count,wordList);
}
wordList.add(word);
}
return countToWordList;
}
//先确定单词对应—>次数 ,再反转次数—>单词,获取出现频数最高的前K个且按字母顺序有序排列打印
public List<String> topKFrequent(String[] words,int k){
Map<String,Integer>wordToCount = count(words);
Map<Integer,List<String>> countToWordList = remap(wordToCount);
// 目的是为了将所有出现次数放到一个int[]中
Set<Integer> keys = countToWordList.keySet(); //调出现次数
int[] counts = new int[keys.size()];
int i = 0;
for(int key: keys){
counts[i++] = key;
}
Arrays.sort(counts);
//录取名单
List<String> result = new ArrayList<>();
int j = 0; //已录取的名单
int index = counts.length - 1; //当前选择的分数,因为从小到大排序
Comparator<String> comparator = new StringComparator(); //按照字母顺序排序
while(j < k){
int c = counts[index--]; //得到最大分
//为了获取当前考c分的人数
List<String> wordList = countToWordList.get(c);
wordList.sort(comparator); //人按照字母排序
if(wordList.size() <= k-j){ //如果当前分数的人数 <= 还差的人数
result.addAll(wordList);
j += wordList.size();
}else{ //否则只选前k-j 个
result.addAll(wordList.subList(0,k-j)); //subList:从list中截取一部分[0,k-j)
j = k;
}
}
return result;
}
public static void main(String[] args) {
String[] words = {
"i","love","leetcode",
"i","love","coding"
};
List<String> r = new P4().topKFrequent(words,3);
System.out.println(r);
}
}
2.输入字母,只打印出大写字母且有序
3.遍历字符串
char[] a =J.toCharArray();
for(char ch: J.toCharArary()){
}
4.得到字符串 Scanner
Scanner scanner = new Scanner(System.in);
String expected = scanner.nextLine();
String actual = scanner.nextLine();
//不区分大小写,统一将字符串转换为大写
char[] a = expected.toUpperCase().toCharArray();
//记录打印出的键
Set<Character> brokenKeys = new HashSet<>();