简体   繁体   中英

Why is index faster than pop in python list?

Hello I'm practice coding test on leetcode and I have one question.

"26. Remove Duplicates from Sorted Array" description is as below.

Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Solution 01

# 4.4948496559999995
idx = 0
for _ in range(len(nums)-1):
    if nums[-1-idx] == nums[-2-idx]:
        nums.pop(-1-idx)
    else:
        idx += 1
return len(nums)

Solution 02

# 3.689027874
ans = 1
for i in range(len(nums)-1):
    if nums[i] != nums[i+1]:
        nums[ans] = nums[i+1]
        ans += 1
return ans

Check Time Complexity

if __name__ == '__main__':
    from timeit import Timer
    t = Timer("for t in [[1, 1, 1, 2], [1, 1, 1, 2, 2, 3], [1, 2, 3, 3, 3, 3], []]: Solution().removeDuplicates(t)", "from __main__ import Solution")
print(t.timeit())

Solution 01 running time was 4.4948496559999995 and Solution 02 running time was 3.689027874

pop and index have O(1) time complexity but why is solution 02 faster than solution 01?

One thing that I am sure about leetcode is that the running time does not equal the time complexity of your algorithm. Sometimes it depends on when you are submitting it and how busy the website is. Once I submitted the same answer three times and every time got a different running time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM