最高频的K个单词和有效的数独

版权声明:欢迎转载哦:http://blog.csdn.net/mikeoperfect(根据全文检索搜索引擎的稀疏矩阵排名算法,这样可以增加排名量哦哈哈哈) https://blog.csdn.net/Mikeoperfect/article/details/81545698

题目:给一个单词列表,求出这个列表中出现频次最高的K个单词。

如果出现频次相同,则以字典序排序

思路:本题并不难,主要需要重新实现一个hashmap根据key值和value值排序的comparator接口即可。但hashmap并没有比较器接口,所以需要把hashmap的entryset导入一个list中,调用Collections.sort方法重新实现comparator接口即可,具体实现代码如下:

public class Solution {
    /**
     * @param words: an array of string
     * @param k: An integer
     * @return: an array of string
     */
    public String[] topKFrequentWords(String[] words, int k) {
        // write your code here
        String[] string=new String[k];
        HashMap<String,Integer> hashMap=new HashMap<>();
        for(int i=0;i<words.length;i++){
            if(hashMap.containsKey(words[i])){
                int val=hashMap.get(words[i]);
                hashMap.put(words[i],++val);
            }else{
                hashMap.put(words[i],1);
            }
        }
        List<Map.Entry<String,Integer>> list=new ArrayList<>(hashMap.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                if(o1.getValue()>o2.getValue()){
                    return -1;
                }else if(o1.getValue()<o2.getValue()){
                    return 1;
                }else{
                    return o1.getKey().compareTo(o2.getKey());
                }
            }
        });
        for(int i=0;i<k;i++){
            string[i]=list.get(i).getKey();
        }
        return string;
    }
}

题目:有效数独

最近脑袋有点傻了,以为i/3*3==i??

这里写图片描述

public boolean isValidSudoku(char[][]board){
        boolean markrow[][]=new boolean[9][10];
        boolean markcow[][]=new boolean[9][10];
        boolean markblock[][]=new boolean[9][10];
        for(int i=0;i<9;i++)
            for(int j=0;j<9;j++){
                int index=i/3*3+j/3;
                if(board[j][i]!='.'){
                    int temp=board[j][i]-'0';
                    if(markrow[j][temp])return false;
                    else markrow[j][temp]=true;
                    if(markcow[i][temp])return false;
                    else markcow[i][temp]=true;
                    if(markblock[index][temp])return false;
                    else markblock[index][temp]=true;
                }
            }
            return true;
    }

小结

秋招也开始了。。。

猜你喜欢

转载自blog.csdn.net/Mikeoperfect/article/details/81545698