Re: [閒聊] 每日LeetCode已回收
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
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 673 之 719 篇):