Concatenation of Array
I did this Leetcode problem. It is fairly straightforward and easy but my first attempt was not the most optimal.
class Solution(object): def getConcatenation(self, nums): """ :type nums: List[int] :rtype: List[int] """ ans = list(nums) for i in nums: ans.append(i) return ans
This was my first attempt. I shallow copied the nums array to ans and then I appended nums to the end of ans. While it is still O(n), it wasn’t the fastest solution.
class Solution: def getConcatenation(self, nums): ans = [] for i in range(2): for n in nums: ans.append(n) return ans
This solution is much more elegant because we can repeat nums 3 times very easily with this code. The outer for loop is constant time since we are only doing it two times. Thus making this solution O(n) time.