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

面試當時沒有及時答出來,感覺當時在面試官的提示下跑偏了。想用兩個數組來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]);
    }
}

 

 

 

  

posted @ 2017-08-16 04:10  simonzhang  阅读(242)  评论(3编辑  收藏  举报