- [Codility] Lession 2.1 CyclicRot
- [Codility] Lession 3.1 TapeEquil
- [Codility] Lession 5.2 CountDiv
- [Codility] Lession 2.2 OddOccurr
- [Codility] Lession 3.3 PermMissi
- [Codility] Lession 3.2 FrogJmp
- [Codility] Lession 4.1 FrogRiver
- [Codility] Lession 4.2 PermCheck
- [Codility] Lession 4.3 MissingIn
- [Codility] Lession 1.1 Binary Ga
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;
}
网友评论