面試當時沒有及時答出來,感覺當時在面試官的提示下跑偏了。想用兩個數組來mapping key和value然後對等排序,但是因為面試官讓用Array.sort而沒想好有什麼好辦法,結果可想而知。但是題目還是要做的,所以,先研究一下這個題目。發現中文搜索沒有找到對應的題目,leetcode上面也沒找到,用英文的找到了怎麼給HashMap按照key和value分別排序的解法。先這樣解決一下。如果誰有更好的解法,歡迎分享。

今天學習到了Java8裡面的簡單寫法,先貼這裡,回家debug一下。

        Map<String, Integer> result2 = new LinkedHashMap<>();
map.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));

把第一種解法這樣改就可以了:

    public static int[] countSort(int[] nums){
if(nums == null || nums.length ==0)
return null;
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i]))
map.put(nums[i], map.get(nums[i]) + 1);
else
map.put(nums[i], 1);
}
        Map<Integer, Integer> resultMap = new LinkedHashMap<>(); 
     map.entrySet().stream()
      .sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed())
      .forEachOrdered(x -> resultMap.put(x.getKey(), x.getValue()));
    int[] result = new int[resultMap.size()]; 
    int i = 0;
    for(Map.Entry<Integer, Integer> entry : resultMap.entrySet()){
       result[i++] = entry.getKey();
    }
    return result;
  }
package ArraySort;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map; public class ArraySort {
public static int[] countSort(int[] nums){
if(nums == null || nums.length ==0)
return null;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i]))
map.put(nums[i], map.get(nums[i]) + 1);
else
map.put(nums[i], 1);
} HashMap<Integer, Integer> resultMap = sortByValue(map); int[] result = new int[resultMap.size()];
int i = 0;
for(Map.Entry<Integer, Integer> entry : resultMap.entrySet()){
result[i++] = entry.getKey();
} return result;
} private static <K, V extends Comparable<? super V>> HashMap<K, V> sortByValue( Map<K, V> map ){
List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
Collections.sort( list, new Comparator<Map.Entry<K, V>>(){
@Override
public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2)
{
return ( o2.getValue() ).compareTo( o1.getValue() );
}
} ); HashMap<K, V> result = new LinkedHashMap<>();
for (Map.Entry<K, V> entry : list)
{
result.put( entry.getKey(), entry.getValue() );
}
return result;
} public static void main(String[] args) {
int[] nums = {2,2,2,2,2,1,1,3,3,3,3};
int[] result = countSort(nums); for(int i = 0; i < result.length; i++)
System.out.println(result[i]);
}
} 下面是调试好的,用二维数组来排序的方式解决问题。
package ArraySort;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set; public class ArraySort {
public static int[] countSort(int[] nums){
if(nums == null || nums.length ==0)
return null;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i]))
map.put(nums[i], map.get(nums[i]) + 1);
else
map.put(nums[i], 1);
} int[][] mapNums= new int[map.size()][2]; Set entries = map.entrySet();
Iterator entriesIterator = entries.iterator(); int i = 0;
while(entriesIterator.hasNext()){ Map.Entry mapping = (Map.Entry) entriesIterator.next(); mapNums[i][0] = (int)mapping.getKey();
mapNums[i][1] = (int)mapping.getValue(); i++;
} int[][] resultMap = sort(mapNums); int[] result = new int[map.size()]; for(int p = 0; p < resultMap.length; p++){
result[p] = resultMap[p][0];
}
return result;
} public static int[][] sort(int[][] arr){
int arr1[] = new int[2];
for(int i = 0; i < arr.length; i++){
for(int j = i; j < arr.length; j++){
if(arr[i][1] < arr[j][1]){
arr1 = arr[i];
arr[i] = arr[j];
arr[j] = arr1;
}
}
} return arr;
} // private static <K, V extends Comparable<? super V>> HashMap<K, V> sortByValue( Map<K, V> map ){
// List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
// Collections.sort( list, new Comparator<Map.Entry<K, V>>(){
// @Override
// public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2)
// {
// return ( o2.getValue() ).compareTo( o1.getValue() );
// }
// } );
//
// HashMap<K, V> result = new LinkedHashMap<>();
// for (Map.Entry<K, V> entry : list)
// {
// result.put( entry.getKey(), entry.getValue() );
// }
// return result;
// } public static void main(String[] args) {
int[] nums = {2,2,2,2,2,1,1,3,3,3,3};
int[] result = countSort(nums); for(int i = 0; i < result.length; i++)
System.out.println(result[i]);
}
}

 

  

最新一道面試題目,input: int[1,1,2,2,2,3,3,3],output [3,2,1],要求按照數字出現的次數從多到少排列元素。的更多相关文章

  1. 一個新的面試題目,leetcode上面可以找到shortest palindrome

    記錄一下新的面試題目,其實題目是舊的,只是我才見到.以前研究過,只不過以前的解法不容易理解,現在有了新的遞歸解法.記錄一下. public String shortestPalindrome(Stri ...

  2. spring框架面試題目

    25个经典的Spring面试问答 这是在网上下载的面试题,忘记了出处,如带来不便联系本人立马删除,在这里提供给将要面试的朋友,与大家分享,希望能给您带来帮助! 问题清单: 1. 什么是Spring框架 ...

  3. List查询重复值的个数,并根据重复的数目从多到少排列

    package ttt; import java.nio.MappedByteBuffer; import java.util.ArrayList; import java.util.Collecti ...

  4. [亂數] <細說> C/C++ 亂數基本使用與常見問題

    陸陸續續寫了 EA  一.二年,以前亂數引導文回頭看時才發現,怎麼有這麼多細節的錯誤.沒系統. 這篇文章主要引導初學者使用亂數,同時附上常被翻出來討論的議題,C/C++適用,唯以 C 語言撰之. 也由 ...

  5. PMP全真模拟题真题試題含答案解析 2019年下半年PMP考試适用 PMP中文文对照试题 【香港台灣地區PMP考試也可用】

    PMP全真模拟题真题试题 含答案解析 2019年下半年PMP考试适用 PMP中文文对照试题 [香港台灣地區PMP考試也可用]PMP全真模擬題真題試題 含答案解析 2019年下半年PMP考試适用 PMP ...

  6. 给定一个只包含正整数的非空数组,返回该数组中重复次数最多的前N个数字 ,返回的结果按重复次数从多到少降序排列(N不存在取值非法的情况)

    """ #给定一个只包含正整数的非空数组,返回该数组中重复次数最多的前N个数字 #返回的结果按重复次数从多到少降序排列(N不存在取值非法的情况) 解题思路: 1.设定一个 ...

  7. 输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

    题目描述 输入一个字符串,按字典序打印出该字符串中字符的所有排列.例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba. 输入描述: 输 ...

  8. js数组操作-找出一组按不同顺序排列的字符串的数组元素

    从一组数组中找出一组按不同顺序排列的字符串的数组元素将字符串转换成数组后再对数组进行 sort 排序,abcd 和 bdca 使用 sort 排序后会变成 abcd,将拍好序的字符串作为对象的 key ...

  9. 根据当前设备的宽度,动态计算出rem的换算比例,实现页面中元素的等比缩放

    ~function anonymous(window){ //根据当前设备的宽度,动态计算出rem的换算比例,实现页面中元素的等比缩放 let computedREM = function compu ...

随机推荐

  1. Win10 修改 开始 菜单样式..

    因为不是平板,所以改成了这个样子 下面说步骤... 打开 菜单栏位置... 将快捷方式 拷贝到 里面 来... 快捷方式 以 #开头.是为了 让其排列在最前面.... 快捷方式有个技巧...快捷方式  ...

  2. Fliptile (dfs+二进制压缩)

    Farmer John knows that an intellectually satisfied cow is a happy cow who will give more milk. He ha ...

  3. 【KMP】【字符串】KMP字符串匹配算法 学习笔记

    一.简介     KMP是由Knuth.Morris和Prat发明的字符串匹配算法,它的时间复杂度是均摊\(O(n+m)\).其实用Hash也可以做到线性,只不过Hash存在极其微小的难以避免的冲突. ...

  4. P1077

    f[i][j]:i种花放j盆的方案数 #include<bits/stdc++.h> using namespace std; const int maxn = 3e2+11; const ...

  5. 修改chrome背景色

    参考:http://blog.csdn.net/jvortex/article/details/73895288 1.新建一个文件夹,比如customcss,包含custom.css和manifest ...

  6. ndoejs解析req,伪造http请求

    require("./m3m4") var http = require('http'); var server = http.createServer(); server.lis ...

  7. 基于docker+redis++urlib/request的分布式爬虫原理

    一.整体思路及中心节点的配置 1.首先在虚拟机中运行一个docker,docker中运行的是一个linux系统,里面有我们所有需要的东西,linux系统,python,mysql,redis以及一些p ...

  8. 7.使用jenkins+marathon+docker完成自动化部署

    1.前置条件 1)Docker开启TCP端口,CloudBees Docker Build and Publish plugin插件会向目标主机docker生成docker镜像 开启docker ap ...

  9. Activemq API使用(整合spring)

    整合spring之后,主要用的就是org.springframework.jms.core.JmsTemplate的API了,在spring-jms-xxx.jar中. 引入整合需要的jar包: &l ...

  10. Java 继承初探

    Java继承的基础 Java中,被继承的类叫做超类,继承超类的类叫子类.(一个子类亦可以是另一个类的超类) 继承一个类,只需要用关键字 extends 把一个类的定义合并到另一个类中就可以了. 例子中 ...