반응형
Problem
이번 문제는 굉장히 메마른 영어지식에 문제를 조금 헷갈렸다 ㅋㅋ
쉽게 2n 길이의 array가 주어지고 각 X1, X2 ...Xn ,Y1 , Y2 ... Yn 이렇게 되어 있다고 보면되고
output에서는 X,Y,X,Y ..... X,Y 이런식으로 교차로 섞인 array를 원하고있다!
이전과 다른 약간 짧은 고민 후에 푼 나의 코드 ( 고민을 했다는 것이 중요하다 )
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
result = list()
for i in range(len(nums)):
result.append(nums[i])
result.append(nums[i+n])
if len(a) == len(nums):
return result
길이가 2n 인 점을 이용하여 새 리스트 Result를 만들어주고 nums의 인덱스 , 인덱스 + 3 을 append 하며 섞어줬다.
길이가 같아지면 return 이번 문제는 뭐 대부분 비슷한 풀이인듯하다
그래도 가장 런타임과 길이가 짦은 코드
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
res = []
for i in range(n):
res.extend([nums[i], nums[i + n]])
return res
오 extend를 사용했다 ! 짧아져서 보기가 좋다!
팁
append
a = list()
a.append(nums[i])
array.append(var)로 사용하고 맨 끝에 객체로 추가해용
i 가 iterable 객체 이더라도 ! 전체를 하나의 객체로 넣어용
Ex)
a = [1,2]
a.append([k,f,c] )
print(a)
# [1,2[k,f,c]]
2) extend 함수
a = list()
a.extend([k,f,c])
array.extend(iterable) 로 사용해용
append 와 다른점은 iterable 객체만 사용 가능하고, iterable 객체의 요소 하나하나를 추가해줘용
a = [k,f,c]
다양한 사고를 공유하는것은 너무 즐거운 일이에용
반응형
'Python > algorithm' 카테고리의 다른 글
[Leetcode] 1672. Richest Customer WealthEasy2.9K305 (0) | 2022.12.26 |
---|---|
[Leetcode] 1512. Number of Good Pairs (0) | 2022.12.25 |
[Leetcode] 2011. Final Value of Variable After Performing Operations (1) | 2022.12.20 |
[Leetcode] 480. Running Sum of 1d Array (1) | 2022.12.19 |
[leetcode] 1108. Defanging an IP Address (2) | 2022.12.19 |