这是我参与8月更文挑战的第10天,活动详情查看:8月更文挑战python
Given an integer array nums of length n, you want to create an array ans of length 2n where ans[i] == nums[i] and ans[i + n] == nums[i] for 0 <= i < n (0-indexed).markdown
Specifically, ans is the concatenation of two nums arrays.app
Return the array ans.less
Example 1:函数
Input: nums = [1,2,1]
Output: [1,2,1,1,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
- ans = [1,2,1,1,2,1]
复制代码
Example 2:oop
Input: nums = [1,3,2,1]
Output: [1,3,2,1,1,3,2,1]
Explanation: The array ans is formed as follows:
- ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
- ans = [1,3,2,1,1,3,2,1]
复制代码
Note:post
n == nums.length
1 <= n <= 1000
1 <= nums[i] <= 1000
复制代码
根据题意,就是要获得两个 nums 拼接而成的字符串并返回,直接将 nums 加两次就行,这也太简单了。。。。优化
class Solution(object):
def getConcatenation(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return nums+nums
复制代码
class Solution(object):
def getConcatenation(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
return nums*2
复制代码
Runtime: 68 ms, faster than 100.00% of Python online submissions for Concatenation of Array.
Memory Usage: 13.8 MB, less than 100.00% of Python online submissions for Concatenation of Array.
复制代码
基本思路同样,就是将 nums 拼接到 nums 以后,还能利用 python 中的 append 函数,在 nums 列表以后,继续追加一次 nums 中的各个元素便可获得答案。spa
class Solution(object):
def getConcatenation(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
for i in range(0,len(nums)):
nums.append(nums[i])
return nums
复制代码
Runtime: 76 ms, faster than 27.80% of Python online submissions for Concatenation of Array.
Memory Usage: 13.6 MB, less than 93.57% of Python online submissions for Concatenation of Array.
复制代码
再优化的方法我也想不出来了,只能想一个最笨的方法了,就是将 nums 中的元素按照顺序加入结果列表 result ,而后再按顺序加入 result 中。不推荐这个方法,有凑字数的嫌疑我深觉得不齿,可是为了凑字数不齿也无法了,幸亏脸皮厚。不过看结果好像这种自认为最慢的方法却不是最慢的,只不过空间所占比较大,嘻嘻。code
class Solution(object):
def getConcatenation(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result = []
N = len(nums)
for i in range(0, 2*N):
result.append(nums[i%N])
return result
复制代码
Runtime: 72 ms, faster than 53.89% of Python online submissions for Concatenation of Array.
Memory Usage: 13.9 MB, less than 14.72% of Python online submissions for Concatenation of Array.
复制代码
原题连接:leetcode.com/problems/co…
您的支持是我最大的动力