list index operation: 0.0006067330032237805 milliseconds list pop(0): 0.0025059110048459843 milliseconds
q2
是证明dict的get和set是O(1),先认为dict的遍历是O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
deftest7(): d = dict(zip(list(range(1000)), list(range(1000,2000)))) for i inrange(1000): d[i] = 1
deftest8(): d = dict(zip(list(range(1000)), list(range(1000,2000)))) for i inrange(1000): k = d[i] deftest9(): d = dict(zip(list(range(1000)), list(range(1000,2000)))) for i inrange(1000): for one in d: pass
dict set item: 0.13327282800310059 milliseconds dict get item: 0.1195711559994379 milliseconds dict iteration: 11.517200201000378 milliseconds
q3
对比list和dict的del操作
1 2 3 4 5 6 7 8 9
deftest10(): l = list(range(1000)) for i inrange(1000): del l[0] deftest11(): d = dict(zip(list(range(1000)), list(range(1000,2000)))) for i inrange(1000): del d[i]
list del item: 0.14648991199646844 milliseconds dict del item: 0.13190877300075954 milliseconds list del item: 0.14080390099843498 milliseconds dict del item: 0.13055396499839844 milliseconds
q4
给定一个list,返回第k小的数。先给出时间复杂度是O(nlogn)的简单版:
1 2 3 4 5 6 7 8 9
defkth_smallest_1(nums, k): """ find kth smallest of a list, O(nlogn) :type nums: list :type k: int :rtype: num """ nums.sort() return nums[k-1]
defkth_smallest_2(nums, k): """ find kth smallest of a list, O(n) :type nums: list :type k: int :rtype: num """ defpartition(nums, start, end): """ Pick last element as pivot Place all smaller elements before pivot Place all bigger elements after pivot """ pivot = nums[end] # currentSmaller 记录当前有几个数比pivot小 currentSmaller = start for i inrange(start, end): # If current element <= pivot, put it to right position if nums[i] <= pivot: nums[i], nums[currentSmaller] = nums[currentSmaller], nums[i] currentSmaller += 1 # Put pivot to right position nums[end], nums[currentSmaller] = nums[currentSmaller], nums[end] return currentSmaller