본문 바로가기
python-algorithm

leetcode 2149. Rearrange Array Elements by Sign

by 무적김두칠 2023. 2. 10.

https://leetcode.com/problems/rearrange-array-elements-by-sign/description/

 

Rearrange Array Elements by Sign - LeetCode

Can you solve this real interview question? Rearrange Array Elements by Sign - You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers. You should rearrange the elements of nums such that

leetcode.com

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
    def rearrangeArray(self, nums: List[int]) -> List[int]:
        answer = []
        positive_nums, negative_nums = [], []
        for i in nums:
            if i>0:
                positive_nums.append(i)
            else:
                negative_nums.append(i)
 
        for i in range(len(nums)//2):
            answer.append(positive_nums[i])
            answer.append(negative_nums[i])
        
        return answer
cs

요구사항에 숫자들 순서가 보존 되어야 하므로
양수와 음수를 순서에 맞게 새로운 리스트에 넣어주고 다시 answer 리스트로 return합니다.

반응형

'python-algorithm' 카테고리의 다른 글

leetcode 234. Palindrome Linked List  (0) 2023.02.11
leetcode 121. Best Time to Buy and Sell Stock  (0) 2023.02.11
leetcode 238. Product of Array Except Self  (0) 2023.02.10
leetcode 15. 3Sum  (0) 2023.02.09
leetcode 42. Trapping Rain Water  (0) 2023.02.09

댓글