def max_k_sort(k, nums):
# sort nums first using timsort
# add O(n*log(n)) time complexity
sorted_nums = sorted(nums)
return sorted_nums[-1*k:len(nums)]
def max_k(k, nums):
# build initial max number list
max_nums = {}
# add O(k) time complexity?
i = 0
while i < k:
max_nums[i] = 0
i += 1
# add O(n) time complexity?
least_max_key = min(max_nums, key=max_nums.get)
least_max = max_nums[least_max_key]
# add O(n) time complexity?
for n in nums:
if n > least_max:
max_nums[least_max_key] = n
least_max_key = min(max_nums, key=max_nums.get)
least_max = max_nums[least_max_key]
return max_nums.values()
print(max_k(5, [2, 8, 4, 9, 0, 12, 12, 6, 5]))
I'm quite unsure of the time complexity of this code. The task is to return the max k numbers from an unsorted integer array. Each number in the array is in the range [0, 10000). My goal is to have one obvious solution max_k_sort(k, nums) that does the task in O(n*log(n)) time complexity and another method max_k(k, nums) that does the task in O(n) time complexity where n is the number of integers passed and k is the number of max values to find. I can't help but wonder if there's a way to return the max values sorted in O(n) time complexity.