Computer Science/알고리즘

[Codility] 2. Array

hyunjin 2023. 12. 16. 22:57

 

2.1 CyclicRotation

An array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is moved to the first place. The goal is to rotate array A K times; that is, each element of A will be shifted to the right K times.
Write a function that, given an array A consisting of N integers and an integer K, returns the array A rotated K times.

N개의 정수로 구성된 배열 A가 주어집니다. 배열의 회전은 각 원소가 한 인덱스만큼 오른쪽으로 이동되고 배열의 마지막 원소가 첫 번째 자리로 이동되는 것을 의미합니다. 배열을 A를 K번 회전시키는 것이 목표입니다. 즉, A의 각 원소는 오른쪽으로 K번 이동될 것입니다.
N개의 정수와 K개의 정수로 구성된 배열 A가 주어졌을 때, 배열 A를 K번 회전하여 되돌려 주는 함수를 쓰시오.

def solution(A, K):
    if len(A) == 0:
        return A
    return A[-(K%len(A)):] + A[:-(K%len(A))]

 

2.2 OddOccurrencesInArray

 

OddOccurrencesInArray coding task - Learn to Code - Codility

Find value that occurs in odd number of elements.

app.codility.com

 

A non-empty array A consisting of N integers is given. The array contains an odd number of elements, and each element of the array can be paired with another element that has the same value, except for one element that is left unpaired.

Write a function that, given an array A consisting of N integers fulfilling the above conditions, returns the value of the unpaired element.

N개의 정수로 구성된 비어 있지 않은 배열 A가 주어집니다. 배열은 홀수 개의 원소를 포함하고 배열의 각 원소는 짝을 이루지 않은 채로 남아 있는 한 원소를 제외하고는 같은 값을 갖는 다른 원소와 짝을 이룰 수 있습니다.

위 조건을 만족하는 N개의 정수로 구성된 배열 A가 주어지면 쌍을 이루지 않은 원소의 값을 반환하는 함수를 작성합니다.

def solution(A):
    tmp = sorted(A)
    res = [ tmp[i] for i in range(0, len(tmp), 2) if i == len(tmp)-1 or tmp[i] != tmp[i+1]]
    return res[0]