2022년 1월 27일 목요일

Codility - 코딩테스트 기록용 2일차

CyclicRotation

 Rotate an array to the right by a given number of steps.

-배열을 주어진 숫자만큼 돌려서 원하는 값을 찾는다

-변경되어야 할 배열순사를 지켜야했음 

-내가 짠 코드

public static int[] solution(int[] A, int K) {

        // write your code in Java SE 8

        int[] result = new int[A.length];

        System.err.println("lenth = "+A.length);

        if(A.length == K){

            return A;

        }     

        

        for (int i = 0; i < A.length ; i++) {

        result[(i+K) % A.length] = A[i];

        System.err.println("i = "+i+" = "+result[i]);

        }

        for (int i = 0; i < result.length; i++) {

System.err.println("a["+i+"] = " +result[i]);

}

        return result;

    }

--다른사람이 짠 코드

class Solution {
    public int[] solution(int[] A, int K) {
        // write your code in Java SE 8
        int len = A.length;
        if(len == 0 || K % len == 0) return A;
        int [] ans = new int [len];

        K = K % len;

        for (int i=0; i< len; i++){
            ans[(i+K) % len] = A[i];
        }
        return ans;
    }
}
역시 개깔끔...나는 멀었나보다
-swift 코드 
public func solution(_ A : inout [Int], _ K : Int) -> [Int] {
    // write your code in Swift 4.2.1 (Linux)
    
    if A.count == K{
        return A
    }
    var result = A
    for i in 0..<A.count{
        let num = (i+K)%A.count
        result[num] = A[i]
    }
    return result
}

댓글 없음:

댓글 쓰기