https://leetcode.com/problems/sort-even-and-odd-indices-independently/description/
Sort Even and Odd Indices Independently - LeetCode
Can you solve this real interview question? Sort Even and Odd Indices Independently - You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules: 1. Sort the values at odd indices of nums in non-increasing o
leetcode.com
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import itertools as it
class Solution:
def sortEvenOdd(self, nums: List[int]) -> List[int]:
odds,evens = [], []
for i in range(len(nums)):
if i%2 == 0:
evens.append(nums[i])
else:
odds.append(nums[i])
odds.sort(reverse = True)
evens.sort()
answer = list(it.chain(*zip(evens, odds)))
if len(odds) < len(evens):
answer.append(evens[-1])
elif len(odds) > len(evens):
answer.append(odds[-1])
return answer
|
cs |
list를 교차로 합치고 싶을때 itertools의 chain 함수를 사용하시면됩니당
Line 15-18의 조건문은 홀수 인덱스와 짝수 인덱스 개수가 다를때는 더 개수가 많은쪽의 마지막 값이 합쳐지지 않아서 따로 예외처리한 부분입니다.
When you want to cross-join a list, you can use itertools' chain function.
The conditional statement in Lines 15-18 is
an exception handling part because when the number of odd indexes and even indexes are different, the last value of the larger number is not combined.
참고 링크:
https://docs.python.org/3/library/itertools.html#itertools.chain
itertools — Functions creating iterators for efficient looping
This module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. Each has been recast in a form suitable for Python. The module standardizes a core set...
docs.python.org
'python-algorithm' 카테고리의 다른 글
leetcode 2549. Count Distinct Numbers on Board (0) | 2023.03.07 |
---|---|
leetcode 1539. Kth Missing Positive Number (0) | 2023.03.06 |
leetcode 203. Remove Linked List Elements (0) | 2023.02.28 |
leetcode 1290. Convert Binary Number in a Linked List to Integer (0) | 2023.02.28 |
leetcode 2574. Left and Right Sum Differences (0) | 2023.02.28 |
댓글