您好,欢迎来到二三娱乐。
搜索
您的当前位置:首页[Codility] Lession 2.1 CyclicRot

[Codility] Lession 2.1 CyclicRot

来源:二三娱乐

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;
}

Copyright © 2019- yule263.com 版权所有 湘ICP备2023023988号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务