Re: [閒聊] 每日LeetCode已回收

看板Marginalman作者 (みけねこ的鼻屎)時間1年前 (2024/02/14 13:13), 編輯推噓1(100)
留言1則, 1人參與, 1年前最新討論串673/719 (看更多)
https://leetcode.com/problems/rearrange-array-elements-by-sign/description 2149. Rearrange Array Elements by Sign 給你一個有相同數量正負數的陣列nums,重新排序他的元素並滿足: 1.整個陣列的元素是:正負正負正負...正負 2.正數和負數的順序和原陣列保持一致。 思路: 1.宣告一個大小相同的list,用一個指標指向正數要插入的地方一個指向負數要插入的 地方,遇到正數就往正數指標位置插入並右移兩格負數同理。 py code ---------------------------------------------- class Solution: def rearrangeArray(self, nums: List[int]) -> List[int]: res = list(range(len(nums))) positiveIndex = 0 negativeIndex = 1 for num in nums: if num > 0: res[positiveIndex] = num positiveIndex += 2 else: res[negativeIndex] = num negativeIndex += 2 return res ---------------------------------------------- 冒充Medium -- https://i.imgur.com/4nfnn6f.jpg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.100.73.13 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1707887581.A.6B9.html

02/14 13:21, 1年前 , 1F
別捲了
02/14 13:21, 1F
文章代碼(AID): #1bp4lTQv (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1bp4lTQv (Marginalman)