leetcode 1929. Concatenation of Array(python)

這是我參與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…

您的支持是我最大的動力

相關文章
相關標籤/搜索