[Codility] Lession 2.1 CyclicRotation

Swift Solution:

import Foundation
public func solution(inout A : [Int], _ K : Int) -> [Int] {
   
    guard A.count > 0 else { return [] }
    guard K > 0 else { return A }
    
    // K is the start index of the sub array which need to be shift to right
   //which means this sub array shall replaced to the left side of the rest
   // such as [1,2,3,4,5,6] shift 3 --> [4,5,6,1,2,3]
    var shiftIdx = K

    // Calculate the valid shift value if K is bigger than A.count
    if K > A.count { shiftIdx = shiftIdx % A.count }
    
    // LeftArray shall be rotated to RIGHT after execution
    let leftArray = A[0 ..< A.count - shiftIdx]
    // RightArray shall be rotated to LEFT after execution
    let rightArray = A[A.count - shiftIdx ..< A.count]
    // Re-order array
    let ordered = rightArray + leftArray
    
    return Array(ordered)
}

Objective-C

-(NSMutableArray*) solution:(NSMutableArray *)A withShift:(int) K{

    if(A.count == 0) { return NULL; }
    if (K <= 0) { return A; }
    
    int shiftIdx = K;
    if (K > A.count) {
        shiftIdx = shiftIdx % A.count;
    }
    NSArray *leftArray = [A subarrayWithRange:NSMakeRange(0, A.count - shiftIdx)];
    NSArray *rightArray = [A subarrayWithRange:NSMakeRange(A.count - shiftIdx , shiftIdx )];
    NSMutableArray *ordered = [NSMutableArray arrayWithArray:[rightArray arrayByAddingObjectsFromArray:leftArray]];
    
    return ordered;
}

你可能感兴趣的:([Codility] Lession 2.1 CyclicRotation)