diff --git a/contains-duplicate/JustHm.swift b/contains-duplicate/JustHm.swift new file mode 100644 index 000000000..10a98dce1 --- /dev/null +++ b/contains-duplicate/JustHm.swift @@ -0,0 +1,5 @@ +class Solution { + func containsDuplicate(_ nums: [Int]) -> Bool { + nums.count != Set(nums).count + } +} diff --git a/house-robber/JustHm.swift b/house-robber/JustHm.swift new file mode 100644 index 000000000..d7230955e --- /dev/null +++ b/house-robber/JustHm.swift @@ -0,0 +1,20 @@ +class Solution { + func rob(_ nums: [Int]) -> Int { + guard nums.count != 1 else { return nums[0] } + guard nums.count != 2 else { return max(nums[0], nums[1]) } + + // var dp = [nums[0], max(nums[0], nums[1])] + var twoStepPrev = nums[0] + var oneStepPrev = max(nums[0], nums[1]) + for i in 2.. Int { + guard !nums.isEmpty else { return 0 } + /* + 중복 제거 후 소팅 후 배열로 만드는것은 N + NlogN + N 으로 예상된다.. + 그래서 정렬만 하고 로직에서 중복 숫자는 그냥 무시하게 만드는 방식으로 속도를 개선 + 문제에서 O(N)으로 작성하자 라는 제약아닌 제약이 있었는데, O(N)은 도저히 떠오르지 않는다. + */ + let nums = nums.sorted()//Array(Set(nums).sorted()) + var answer = 1 + var count = 1 + for index in 0.. Int { + var numSet = Set(nums) + var answer = 0 + + for num in numSet { + // num-1이 없으면 시작지점이니까 여기부터 +1 하면서 길이 확인 + // num-1이 있으면 그냥 무시 + if !numSet.contains(num-1) { //Set의 contains는 O(1)임!! (내부적으로 Hash table로 구현되어있기 때문) + var count = 1 + var temp = num + 1 + while numSet.contains(temp) { + count += 1 + temp += 1 + } + answer = max(answer, count) + } + } + return answer + } +} diff --git a/top-k-frequent-elements/JustHm.swift b/top-k-frequent-elements/JustHm.swift new file mode 100644 index 000000000..e80dc9370 --- /dev/null +++ b/top-k-frequent-elements/JustHm.swift @@ -0,0 +1,44 @@ +// MARK: 리뷰를 받고 시도해본 다른 풀이 (time: O(n), space O(n) +class Solution { + func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] { + // 빈도수 별로 Dictionary에 저장 + var dict = [Int: Int]() + for num in nums { + dict[num, default: 0] += 1 + } + // Bucket sort 사용, 크기는 nums 만큼, 빈도수가 nums 공간보다 클수는 없으니까 + var bucket = Array(repeating: [Int](), count: nums.count + 1) + for (key, value) in dict { + // 빈도수를 인덱스로 key == num 을 저장함 + // 배열로 한 이유는 빈도수가 같은게 있을 수 있으니까! + bucket[value].append(key) + } + + // 결과 출력 + var answer = [Int]() + // bucket의 뒤에서부터 탐색 + for index in stride(from: nums.count, to: 0, by: -1) { + // 없으면 무시 + guard !bucket[index].isEmpty else { continue } + // 버켓의 현재 인덱스에 nil이 아니면 하나씩 결과에 추가해줌. + for item in bucket[index] { + answer.append(item) + // k개 만큼 가져왔다면 바로 리턴 + if answer.count == k { return answer } + } + } + + return answer + } +} +// MARK: time: O(nlogn), space: O(n) +// n+nlogn+n +class Solution { + func topKFrequent(_ nums: [Int], _ k: Int) -> [Int] { + var dict = [Int: Int]() + for num in nums { + dict[num, default: 0] += 1 + } + return [Int](dict.sorted{$0.value > $1.value}.map{$0.key}[.. [Int] { + var dict = [Int: Int]() + for index in 0..