Skip to content

Commit 48bc8ab

Browse files
committed
commented further
1 parent 7a3fb03 commit 48bc8ab

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

LuoSonglei/week-97/347-TopkFrequentElements.c

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ void swap(int* p, int* q)
1515
int t=*p; *p=*q; *q=t;
1616
}
1717

18-
void sort(int* nums, int* counters, int begin, int end)
18+
//Sort the array nums and keep its indexes along with it;
19+
void sort(int* nums, int* indexes, int begin, int end)
1920
{
2021
int l=begin, r=end;
2122
int v = nums[l+(r-l)/2];
@@ -25,24 +26,24 @@ void sort(int* nums, int* counters, int begin, int end)
2526
while(nums[r] > v) r--;
2627
if(l <= r)
2728
{
28-
swap(counters+l, counters+r);
29+
swap(indexes+l, indexes+r);
2930
swap(nums+l++, nums+r--);
3031
}
3132
}
3233
if(begin < r)
33-
sort(nums, counters, begin, r);
34+
sort(nums, indexes, begin, r);
3435
if(l < end)
35-
sort(nums, counters, l, end);
36+
sort(nums, indexes, l, end);
3637
}
3738

3839
//AC - 24ms;
3940
int* topKFrequent(int* nums, int size, int k, int* returnSize)
4041
{
4142
int* indexes = (int*)malloc(sizeof(int)*size);
42-
int* arr = (int*)malloc(sizeof(int)*size);
43-
sort(nums, arr, 0, size-1);
43+
int* arr = (int*)malloc(sizeof(int)*size); //used to count and also be used as return array;
44+
sort(nums, arr, 0, size-1); //arr here is used for parameter position-taker, nothing more;
4445
int top = -1;
45-
for(int i = 0; i < size; i++)
46+
for(int i = 0; i < size; i++) //count elements, recording its first index and frequency;
4647
{
4748
if(top==-1 || nums[indexes[top]]!=nums[i])
4849
{
@@ -51,8 +52,8 @@ int* topKFrequent(int* nums, int size, int k, int* returnSize)
5152
}
5253
else arr[top]++;
5354
}
54-
sort(arr, indexes, 0, top);
55-
for(int i = 0; i < k; i++)
55+
sort(arr, indexes, 0, top); //make the frequency array arr in ascending order;
56+
for(int i = 0; i < k; i++) //collect the first k most frequent elements;
5657
arr[i] = nums[indexes[top-i]];
5758
*returnSize = k;
5859
return arr;

0 commit comments

Comments
 (0)