LeetCode: Top K Frequent Elements C#Leetcode 210. Course Schedule IIBrick Wall Leetcode challengeGiven some...
how to know this integral finite or infinite
What is this WWII four-engine plane on skis?
Have you ever been issued a passport or national identity card for travel by any other country?
Answer not a fool, or answer a fool?
Is there a generally agreed upon solution to Bradley's Infinite Regress without appeal to Paraconsistent Logic?
How often is duct tape used during crewed space missions?
Why are there no programmes / playbills for movies?
How would you translate Evangelii Nuntiandi?
What are some examples of research that does not solve a existing problem (maybe the problem is not obvious yet) but present a unique discovery?
How do we know that black holes are spinning?
Why 1.5fill is 0pt
Bash attempts to write two shell prompts?
Is it possible that the shadow of the moon is a single dot during solar eclipse?
Talk about Grandpa's weird talk: Who are these folks?
Hobby function generators
What is the word for a person who destroys monuments?
Electrosynthetic Autotrophs
What does the "capacitor into resistance" symbol mean?
Why is it called a stateful and a stateless firewall?
Wrong Schengen Visa exit stamp on my passport, who can I complain to?
Why is the return value of the fun function 8 instead of 7?
Unpredictability of Stock Market
Why does an orbit become hyperbolic when total orbital energy is positive?
Amortized Loans seem to benefit the bank more than the customer
LeetCode: Top K Frequent Elements C#
Leetcode 210. Course Schedule IIBrick Wall Leetcode challengeGiven some integers, return the k most frequent elementsLeetcode 54: Spiral MatrixTwo Sum LeetcodeLeetCode gas station implementationLeetCode: Employee-importance BFSLeetCode: Pascal's Triangle C#
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}
$begingroup$
https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799
Given a non-empty array of integers, return the k most frequent
elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1] 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.
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
//good example for bucket sort
namespace SortingQuestions
{
/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799
/// </summary>
[TestClass]
public class TopKFrequentTest
{
[TestMethod]
public void SimpleUseCaseTest()
{
int[] nums = { 1, 1, 1, 2, 2, 3 };
int k = 2;
int[] expected = { 1, 2 };
CollectionAssert.AreEqual(expected, TopKFrequentClass.TopKFrequent(nums, k).ToArray());
}
}
public class TopKFrequentClass
{
public static IList<int> TopKFrequent(int[] nums, int k)
{
Dictionary<int, int> number2Count = new Dictionary<int, int>();
//we count how many times each number appears
foreach (var num in nums)
{
number2Count.TryGetValue(num, out var temp);
number2Count[num] = temp + 1;
}
List<int>[] bucket = new List<int>[nums.Length + 1];
//we allocate an array in the size of the original list of numbers
//we iterate all of the numbers and for add each number to the index in the array
// the index represents how many times that number appeared
//
// 0 times -> none
// 1 times -> number 3
// 2 times -> number 2
// 3 times -> number 1
// 4 times -> none
// 5 times -> none
foreach (var key in number2Count.Keys)
{
int frequency = number2Count[key];
if (bucket[frequency] == null)
{
bucket[frequency] = new List<int>();
}
bucket[frequency].Add(key);
}
List<int> result = new List<int>();
// we iterate the list bucket in reverse until the number of items in the result
// list equals k, because we iterate in reserve we get the biggest numbers
for (int pos = bucket.Length - 1; pos >= 0 && result.Count < k; pos--)
{
if (bucket[pos] != null)
{
result.AddRange(bucket[pos]);
}
}
return result;
}
}
}
I really like this question and it took me some time to understand how to implement the bucket sorting.
I know I can also use MaxHeap.
Since C# doesn't have a MaxHeap, do you think using a SortedList can help here somehow with the performance? (remember the question limitations)
I am mainly looking for performance optimizations.
c# programming-challenge sorting bucket-sort
$endgroup$
add a comment
|
$begingroup$
https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799
Given a non-empty array of integers, return the k most frequent
elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1] 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.
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
//good example for bucket sort
namespace SortingQuestions
{
/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799
/// </summary>
[TestClass]
public class TopKFrequentTest
{
[TestMethod]
public void SimpleUseCaseTest()
{
int[] nums = { 1, 1, 1, 2, 2, 3 };
int k = 2;
int[] expected = { 1, 2 };
CollectionAssert.AreEqual(expected, TopKFrequentClass.TopKFrequent(nums, k).ToArray());
}
}
public class TopKFrequentClass
{
public static IList<int> TopKFrequent(int[] nums, int k)
{
Dictionary<int, int> number2Count = new Dictionary<int, int>();
//we count how many times each number appears
foreach (var num in nums)
{
number2Count.TryGetValue(num, out var temp);
number2Count[num] = temp + 1;
}
List<int>[] bucket = new List<int>[nums.Length + 1];
//we allocate an array in the size of the original list of numbers
//we iterate all of the numbers and for add each number to the index in the array
// the index represents how many times that number appeared
//
// 0 times -> none
// 1 times -> number 3
// 2 times -> number 2
// 3 times -> number 1
// 4 times -> none
// 5 times -> none
foreach (var key in number2Count.Keys)
{
int frequency = number2Count[key];
if (bucket[frequency] == null)
{
bucket[frequency] = new List<int>();
}
bucket[frequency].Add(key);
}
List<int> result = new List<int>();
// we iterate the list bucket in reverse until the number of items in the result
// list equals k, because we iterate in reserve we get the biggest numbers
for (int pos = bucket.Length - 1; pos >= 0 && result.Count < k; pos--)
{
if (bucket[pos] != null)
{
result.AddRange(bucket[pos]);
}
}
return result;
}
}
}
I really like this question and it took me some time to understand how to implement the bucket sorting.
I know I can also use MaxHeap.
Since C# doesn't have a MaxHeap, do you think using a SortedList can help here somehow with the performance? (remember the question limitations)
I am mainly looking for performance optimizations.
c# programming-challenge sorting bucket-sort
$endgroup$
add a comment
|
$begingroup$
https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799
Given a non-empty array of integers, return the k most frequent
elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1] 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.
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
//good example for bucket sort
namespace SortingQuestions
{
/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799
/// </summary>
[TestClass]
public class TopKFrequentTest
{
[TestMethod]
public void SimpleUseCaseTest()
{
int[] nums = { 1, 1, 1, 2, 2, 3 };
int k = 2;
int[] expected = { 1, 2 };
CollectionAssert.AreEqual(expected, TopKFrequentClass.TopKFrequent(nums, k).ToArray());
}
}
public class TopKFrequentClass
{
public static IList<int> TopKFrequent(int[] nums, int k)
{
Dictionary<int, int> number2Count = new Dictionary<int, int>();
//we count how many times each number appears
foreach (var num in nums)
{
number2Count.TryGetValue(num, out var temp);
number2Count[num] = temp + 1;
}
List<int>[] bucket = new List<int>[nums.Length + 1];
//we allocate an array in the size of the original list of numbers
//we iterate all of the numbers and for add each number to the index in the array
// the index represents how many times that number appeared
//
// 0 times -> none
// 1 times -> number 3
// 2 times -> number 2
// 3 times -> number 1
// 4 times -> none
// 5 times -> none
foreach (var key in number2Count.Keys)
{
int frequency = number2Count[key];
if (bucket[frequency] == null)
{
bucket[frequency] = new List<int>();
}
bucket[frequency].Add(key);
}
List<int> result = new List<int>();
// we iterate the list bucket in reverse until the number of items in the result
// list equals k, because we iterate in reserve we get the biggest numbers
for (int pos = bucket.Length - 1; pos >= 0 && result.Count < k; pos--)
{
if (bucket[pos] != null)
{
result.AddRange(bucket[pos]);
}
}
return result;
}
}
}
I really like this question and it took me some time to understand how to implement the bucket sorting.
I know I can also use MaxHeap.
Since C# doesn't have a MaxHeap, do you think using a SortedList can help here somehow with the performance? (remember the question limitations)
I am mainly looking for performance optimizations.
c# programming-challenge sorting bucket-sort
$endgroup$
https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799
Given a non-empty array of integers, return the k most frequent
elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums = [1], k = 1
Output: [1] 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.
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
//good example for bucket sort
namespace SortingQuestions
{
/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-medium/110/sorting-and-searching/799
/// </summary>
[TestClass]
public class TopKFrequentTest
{
[TestMethod]
public void SimpleUseCaseTest()
{
int[] nums = { 1, 1, 1, 2, 2, 3 };
int k = 2;
int[] expected = { 1, 2 };
CollectionAssert.AreEqual(expected, TopKFrequentClass.TopKFrequent(nums, k).ToArray());
}
}
public class TopKFrequentClass
{
public static IList<int> TopKFrequent(int[] nums, int k)
{
Dictionary<int, int> number2Count = new Dictionary<int, int>();
//we count how many times each number appears
foreach (var num in nums)
{
number2Count.TryGetValue(num, out var temp);
number2Count[num] = temp + 1;
}
List<int>[] bucket = new List<int>[nums.Length + 1];
//we allocate an array in the size of the original list of numbers
//we iterate all of the numbers and for add each number to the index in the array
// the index represents how many times that number appeared
//
// 0 times -> none
// 1 times -> number 3
// 2 times -> number 2
// 3 times -> number 1
// 4 times -> none
// 5 times -> none
foreach (var key in number2Count.Keys)
{
int frequency = number2Count[key];
if (bucket[frequency] == null)
{
bucket[frequency] = new List<int>();
}
bucket[frequency].Add(key);
}
List<int> result = new List<int>();
// we iterate the list bucket in reverse until the number of items in the result
// list equals k, because we iterate in reserve we get the biggest numbers
for (int pos = bucket.Length - 1; pos >= 0 && result.Count < k; pos--)
{
if (bucket[pos] != null)
{
result.AddRange(bucket[pos]);
}
}
return result;
}
}
}
I really like this question and it took me some time to understand how to implement the bucket sorting.
I know I can also use MaxHeap.
Since C# doesn't have a MaxHeap, do you think using a SortedList can help here somehow with the performance? (remember the question limitations)
I am mainly looking for performance optimizations.
c# programming-challenge sorting bucket-sort
c# programming-challenge sorting bucket-sort
edited 1 hour ago
dfhwze
11.7k2 gold badges22 silver badges77 bronze badges
11.7k2 gold badges22 silver badges77 bronze badges
asked 8 hours ago
GiladGilad
2,0903 gold badges19 silver badges41 bronze badges
2,0903 gold badges19 silver badges41 bronze badges
add a comment
|
add a comment
|
1 Answer
1
active
oldest
votes
$begingroup$
I think that in terms of performance you'd be hard pressed to do better than a LINQ query. Not only fast but very compact and relatively easy to understand. It could look something like this:
public IList<int> TopKFrequent(int[] nums, int k) {
var answer = (from int n in nums
group n by n into g
orderby g.Count() descending
select g.Key).Take((k)).ToList();
return answer;
}
$endgroup$
1
$begingroup$
Isn't this sorting nlogn?
$endgroup$
– Gilad
1 hour ago
add a comment
|
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f229076%2fleetcode-top-k-frequent-elements-c%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
I think that in terms of performance you'd be hard pressed to do better than a LINQ query. Not only fast but very compact and relatively easy to understand. It could look something like this:
public IList<int> TopKFrequent(int[] nums, int k) {
var answer = (from int n in nums
group n by n into g
orderby g.Count() descending
select g.Key).Take((k)).ToList();
return answer;
}
$endgroup$
1
$begingroup$
Isn't this sorting nlogn?
$endgroup$
– Gilad
1 hour ago
add a comment
|
$begingroup$
I think that in terms of performance you'd be hard pressed to do better than a LINQ query. Not only fast but very compact and relatively easy to understand. It could look something like this:
public IList<int> TopKFrequent(int[] nums, int k) {
var answer = (from int n in nums
group n by n into g
orderby g.Count() descending
select g.Key).Take((k)).ToList();
return answer;
}
$endgroup$
1
$begingroup$
Isn't this sorting nlogn?
$endgroup$
– Gilad
1 hour ago
add a comment
|
$begingroup$
I think that in terms of performance you'd be hard pressed to do better than a LINQ query. Not only fast but very compact and relatively easy to understand. It could look something like this:
public IList<int> TopKFrequent(int[] nums, int k) {
var answer = (from int n in nums
group n by n into g
orderby g.Count() descending
select g.Key).Take((k)).ToList();
return answer;
}
$endgroup$
I think that in terms of performance you'd be hard pressed to do better than a LINQ query. Not only fast but very compact and relatively easy to understand. It could look something like this:
public IList<int> TopKFrequent(int[] nums, int k) {
var answer = (from int n in nums
group n by n into g
orderby g.Count() descending
select g.Key).Take((k)).ToList();
return answer;
}
answered 5 hours ago
tinstaafltinstaafl
7,5871 gold badge9 silver badges31 bronze badges
7,5871 gold badge9 silver badges31 bronze badges
1
$begingroup$
Isn't this sorting nlogn?
$endgroup$
– Gilad
1 hour ago
add a comment
|
1
$begingroup$
Isn't this sorting nlogn?
$endgroup$
– Gilad
1 hour ago
1
1
$begingroup$
Isn't this sorting nlogn?
$endgroup$
– Gilad
1 hour ago
$begingroup$
Isn't this sorting nlogn?
$endgroup$
– Gilad
1 hour ago
add a comment
|
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f229076%2fleetcode-top-k-frequent-elements-c%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown