[Swift]LeetCode692. 前K個高頻單詞 | Top K Frequent Words

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-wzrbftyx-me.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given a non-empty list of words, return the k most frequent elements.git

Your answer should be sorted by frequency from highest to lowest. If two words have the same frequency, then the word with the lower alphabetical order comes first.github

Example 1:微信

Input: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
Output: ["i", "love"]
Explanation: "i" and "love" are the two most frequent words.
    Note that "i" comes before "love" due to a lower alphabetical order. 

Example 2:app

Input: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
Output: ["the", "is", "sunny", "day"]
Explanation: "the", "is", "sunny" and "day" are the four most frequent words,
    with the number of occurrence being 4, 3, 2 and 1 respectively. 

Note:ide

  1. You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
  2. Input words contain only lowercase letters. 

Follow up:spa

  1. Try to solve it in O(n log k) time and O(n) extra space.

給一非空的單詞列表,返回前 個出現次數最多的單詞。code

返回的答案應該按單詞出現頻率由高到低排序。若是不一樣的單詞有相同出現頻率,按字母順序排序。htm

示例 1:blog

輸入: ["i", "love", "leetcode", "i", "love", "coding"], k = 2
輸出: ["i", "love"]
解析: "i" 和 "love" 爲出現次數最多的兩個單詞,均爲2次。
    注意,按字母順序 "i" 在 "love" 以前。 

示例 2:

輸入: ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"], k = 4
輸出: ["the", "is", "sunny", "day"]
解析: "the", "is", "sunny" 和 "day" 是出現次數最多的四個單詞,
    出現次數依次爲 4, 3, 2 和 1 次。 

注意:

  1. 假定 k 總爲有效值, 1 ≤ k ≤ 集合元素數。
  2. 輸入的單詞均由小寫字母組成。 

擴展練習:

  1. 嘗試以 O(n log k) 時間複雜度和 O(n) 空間複雜度解決。

76ms

 1 class Solution {
 2     func topKFrequent(_ words: [String], _ k: Int) -> [String] {
 3         var frequencyList = [String:Int]()
 4         for word in words {
 5             if let count = frequencyList[word] {
 6                 frequencyList[word] = count + 1
 7             } else {
 8                 frequencyList[word] = 1
 9             }
10         }
11         let b = frequencyList.sorted { (dic1, dic2) -> Bool in
12             if dic1.value != dic2.value {
13                 return dic1.value > dic2.value
14             } else {
15                 return dic1.key < dic2.key
16             }
17         }
18         var result = [String]()
19         for item in b {
20             result.append(item.key)
21             if result.count == k {
22                 return result
23             }
24         }
25         return result
26     }
27 }

Runtime: 88 ms
Memory Usage: 20.4 MB
 1 class Solution {
 2     func topKFrequent(_ words: [String], _ k: Int) -> [String] {
 3         var k = k
 4         var res:[String] = [String]()
 5         var freq:[String:Int] = [String:Int]()
 6         var v:[Set<String>] = [Set<String>](repeating:Set<String>(),count:words.count + 1)
 7         for word in words
 8         {
 9             freq[word,default:0] += 1
10         }
11         for (key,val) in freq
12         {
13             v[val].insert(key)
14         }
15         for i in stride(from:v.count - 1,through:0,by:-1)
16         {
17             if k <= 0 {break}
18             var t:[String] = v[i].sorted()
19             if k >= t.count
20             {               
21                 res += t
22             }
23             else
24             {
25 
26                  res += t[0..<k]
27             }
28             k -= t.count
29         }
30         return res
31     }
32 }

88ms

 1 class Solution {
 2     func topKFrequent(_ words: [String], _ k: Int) -> [String] {
 3         var countMap = [String: Int]()
 4         var firstAppearance = [String: Int]()
 5         for (i, word) in words.enumerated() {
 6             countMap[word, default: 0] += 1 
 7             if firstAppearance[word] == nil {
 8                 firstAppearance[word] = i
 9             }
10         }
11         var sortedStringsBasedOnCount = countMap.sorted {
12             return $0.value > $1.value || 
13             ($0.value == $1.value && $0.key < $1.key)
14         }
15         return sortedStringsBasedOnCount[0..<k].map { $0.0 }
16     }
17 }

92ms

 1 class Solution {
 2     func topKFrequent(_ words: [String], _ k: Int) -> [String] {
 3         var countMap = [String: Int]()
 4         words.forEach { countMap[$0, default: 0] += 1 }
 5         var sortedStringsBasedOnCount = countMap.sorted {
 6             return $0.value > $1.value || 
 7             ($0.value == $1.value && $0.key < $1.key)
 8         }
 9         return sortedStringsBasedOnCount[0..<k].map { $0.0 }
10     }
11 }

96ms

 1 class Solution {
 2     func topKFrequent(_ words: [String], _ k: Int) -> [String] {
 3         var wordDict = [String : Int]()
 4         for word in words {
 5             wordDict[word] = 1 + (wordDict[word] ?? 0)
 6         }
 7         return wordDict.sorted { 
 8             $0.value > $1.value || $0.value == $1.value && $0.key < $1.key
 9         }[0..<k].map{$0.key}
10     }
11 }

100ms

 1 class Solution {
 2     func topKFrequent(_ words: [String], _ k: Int) -> [String] {
 3         var frequencyList = [String:Int]()
 4         for word in words {
 5             if let count = frequencyList[word] {
 6                 frequencyList[word] = count + 1
 7             } else {
 8                 frequencyList[word] = 1
 9             }
10         }
11         var frequencyList2 = [[String]](repeating:[String](), count:words.count)
12         for (key, value) in frequencyList {
13             frequencyList2[value].append(key)
14             frequencyList2[value] = frequencyList2[value].sorted()
15         }
16         frequencyList2 = frequencyList2.filter{$0 != [String]()}
17         var result = [String]()
18         var index = frequencyList2.count - 1
19         while index >= 0 {
20             for item in frequencyList2[index] {
21                 result.append(item)
22                 if result.count == k {
23                     return result
24                 }
25             }
26             index -= 1
27         }
28         return result
29     }
30 }

128ms

 1 class Solution {
 2        func topKFrequent(_ words: [String], _ k: Int) -> [String] {
 3         guard words.count > 0 else {
 4             return [String]()
 5         }
 6         
 7         var memo = [String:Int]()
 8         
 9         for w in words {
10             memo[w] = memo[w, default:0] + 1
11         }
12         
13         var helpArray = [[String]]()
14         
15         for key in memo.keys {
16             if let count = memo[key] {
17                 helpArray.append([String(count), key])
18             }
19         }
20         
21         helpArray.sort(by:{
22             if Int($0[0])! > Int($1[0])! {
23                 return true
24             } else if Int($0[0])! < Int($1[0])! {
25                 return false
26             } else {
27                 return $0[1] < $1[1]
28             }
29         })        
30         var sortedArray = helpArray.map{ $0[1] }
31         
32         return Array(sortedArray[0...k - 1])
33     }
34 }
相關文章
相關標籤/搜索