staticinlineintcmp(constvoid *pa, constvoid *pb) { int a = *(int *)pa; int b = *(int *)pb; int cnta = hashGetItem(&cnt, a, 0); int cntb = hashGetItem(&cnt, b, 0); if (cnta != cntb) { return cnta - cntb; } return b - a; }
int* frequencySort(int* nums, int numsSize, int* returnSize) { cnt = NULL; for (int i = 0; i < numsSize; i++) { hashSetItem(&cnt, nums[i], hashGetItem(&cnt, nums[i], 0) + 1); } qsort(nums, numsSize, sizeof(int), cmp); hashFree(&cnt); *returnSize = numsSize; return nums; }
[sol1-JavaScript]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
var frequencySort = function(nums) { const cnt = newMap(); for (const num of nums) { cnt.set(num, (cnt.get(num) || 0) + 1); } const list = [...nums]; list.sort((a, b) => { const cnt1 = cnt.get(a), cnt2 = cnt.get(b); return cnt1 !== cnt2 ? cnt1 - cnt2 : b - a; }); const length = nums.length; for (let i = 0; i < length; i++) { nums[i] = list[i]; } return nums; };
[sol1-Golang]
1 2 3 4 5 6 7 8 9 10 11
funcfrequencySort(nums []int) []int { cnt := map[int]int{} for _, x := range nums { cnt[x]++ } sort.Slice(nums, func(i, j int)bool { a, b := nums[i], nums[j] return cnt[a] < cnt[b] || cnt[a] == cnt[b] && a > b }) return nums }