Last active
September 22, 2018 01:25
-
-
Save yojkim/133d4a943e7209d621cc03c2d809bea2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func topKFrequent(nums []int, k int) []int { | |
cnt := make(map[int]int) | |
idx := make(map[int]int) | |
res := []int{} | |
for _, x := range nums { | |
cnt[x]++ | |
if cnt[x] != 1 { | |
moveTo := -1 | |
for i:=idx[x]-1; i>=0; i-- { | |
if cnt[res[i]] < cnt[x] { | |
moveTo = i | |
idx[res[i]]++ | |
} else { | |
break | |
} | |
} | |
if moveTo != -1 { | |
tmp := []int{} | |
for _, n := range res[:moveTo] { | |
tmp = append(tmp, n) | |
} | |
tmp = append(tmp, x) | |
for _, n := range res[moveTo:] { | |
if n != x { | |
tmp = append(tmp, n) | |
} | |
} | |
res = tmp | |
idx[x] = moveTo | |
} | |
} else { | |
res = append(res, x) | |
idx[x] = len(res)-1 | |
} | |
} | |
return res[:k] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment