잡다로그

[99클럽 코테 스터디] 15일차 TIL - 배열, Shuffle the Array 본문

Algorithm

[99클럽 코테 스터디] 15일차 TIL - 배열, Shuffle the Array

날으는다람쥐 2024. 6. 15. 01:41

[15일차] 배열

문제: https://leetcode.com/problems/shuffle-the-array/description/

Solution

class Solution(object):
    def shuffle(self, nums, n):
        """
        :type nums: List[int]
        :type n: int
        :rtype: List[int]
        """
        x = nums[0:n]   # 0부터 n-1까지, n개
        y = nums[n:2*n] # n부터 2*n-1까지 n개
        result = []
        
        for i in range(n):
            result.append(x[i])
            result.append(y[i])

        return result

Another Solution

나는 배열 슬라이싱을 이용했지만, 굳이 변수를 만들지 않고 인덱스만을 활용해서 정답을 출력하는 방법도 있다.

class Solution(object):
    def shuffle(self, nums, n):
        leng = len(nums)
        j = n
        a=[]
        for i in range(n):
            a.append(nums[i])
            a.append(nums[j])
            j+=1
        return a

나다어

  • 파이썬 인덱스 슬라이싱은 [n:k]로 쓰고, n부터 k-1까지 슬라이싱한다. k는 포함 안됨 주의!
  • 배열 문제는 인덱스를 적극적으로 활용하자.
Comments