摘要:解題思路,默認(rèn)就是隊列頂端是最小元素,第大元素,我們只要限制的大小為即可,最后隊列頂端的就是第大元素。代碼解題思路利用存入,之后采用,并限制最多放個元素。
Kth Largest Element in an Array
Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.
For example, Given [3,2,1,5,6,4] and k = 2, return 5.
Note:
You may assume k is always valid, 1 ≤ k ≤ array"s length.
1.解題思路
PriorityQueue,默認(rèn)就是隊列頂端是最小元素,第k大元素,我們只要限制queue的大小為k即可,最后隊列頂端的就是第k大元素。
2.代碼
public class Solution { public int findKthLargest(int[] nums, int k) { if(nums.length==0) return -1; PriorityQueuepq=new PriorityQueue (); for(int i=0;i pq.peek()){ pq.poll(); pq.add(nums[i]); } } return pq.peek(); } }
Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
For example, Given [1,1,1,2,2,3] and k = 2, return [1,2].
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm"s time complexity must be better than O(n log n), where n is the array"s size.
1.解題思路
利用HashMap存入
2.代碼
public class Solution { public ListtopKFrequent(int[] nums, int k) { List res=new ArrayList (); if(nums.length==0) return res; Map map=new HashMap ();// for(int i=0;i > pq=new PriorityQueue >(new Comparator >(){ public int compare(Map.Entry a,Map.Entry b){ return a.getValue()-b.getValue(); } }); for(Map.Entry entry:map.entrySet()){ pq.add(entry); if(pq.size()>k) pq.poll(); } while(pq.size()>0){ Map.Entry entry=pq.poll(); res.add(0,entry.getKey()); } return res; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/69824.html
摘要:優(yōu)先隊列復(fù)雜度時間空間思路遍歷數(shù)組時將數(shù)字加入優(yōu)先隊列堆,一旦堆的大小大于就將堆頂元素去除,確保堆的大小為。如果這個分界點(diǎn)是,說明分界點(diǎn)的數(shù)就是第個數(shù)。 Kth Largest Element in an Array Find the kth largest element in an unsorted array. Note that it is the kth largest e...
摘要:可以不要用太簡單的方法。先把它裝滿,再和隊列頂端的數(shù)字比較,大的就替換掉,小的就。遍歷完所有元素之后,頂部的數(shù)就是第大的數(shù)。 Problem Find K-th largest element in an array. Example In array [9,3,2,4,8], the 3rd largest element is 4.In array [1,2,3,4,5], the...
摘要:先按照元素次數(shù)的將所有元素存入,再按照次數(shù)元素將哈希表里的所有元素存入,然后取最后的個元素返回。 Problem Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2,2,3] and k = 2, return [1,2]. Note: ...
python 數(shù)據(jù)結(jié)構(gòu) map # init map_ = {} map_ = {shiyang: 0, heanni: 1, china: 2} # existence print shiyang in map_ # add print map_[shiyang] # delete map_.pop(shiyang) #traverse for k in map_.keys(): pr...
Problem Implement a data structure, provide two interfaces: add(number). Add a new number in the data structure.topk(). Return the top k largest numbers in this data structure. k is given when we crea...
閱讀 2474·2021-11-16 11:45
閱讀 2444·2021-10-11 10:59
閱讀 2251·2021-10-08 10:05
閱讀 3817·2021-09-23 11:30
閱讀 2370·2021-09-07 09:58
閱讀 790·2019-08-30 15:55
閱讀 773·2019-08-30 15:53
閱讀 1923·2019-08-29 17:00