heydoy / codility-swift Goto Github PK
View Code? Open in Web Editor NEWcodility 사이트 exercise를 푸는 곳
codility 사이트 exercise를 푸는 곳
문제: https://app.codility.com/c/run/trainingHPTSXQ-BB6/
문제가 잘 이해가 안된다. 어떻게 풀어야할지도.
import Foundation
import Glibc
// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 4.2.1 (Linux)
// dicitonary 를 만들어서 저장하자
var dict: [Int: Int] = [:]
for item in A {
if let value = dict[item] {
dict[item] = value + 1
} else {
dict[item] = 1
}
}
for number in A {
if dict[number] == 1 {
return number
}
}
return -1
}
extension String {
subscript(idx: Int) -> String? {
guard (0..<count).contains(idx) else {
return nil
}
let target = index(startIndex, offsetBy: idx)
return String(self[target])
}
subscript(_ range: CountableRange<Int>) -> String {
let start = index(startIndex, offsetBy: max(0, range.lowerBound))
let end = index(startIndex, offsetBy: min(self.count, range.upperBound))
return String(self[start..<end])
}
subscript(_ range: CountablePartialRangeFrom<Int>) -> String {
let start = index(startIndex, offsetBy: max(0, range.lowerBound))
return String(self[start...])
}
}
public func solution(_ S : inout String) -> Int {
// write your code in Swift 4.2.1 (Linux)
if S.count % 2 == 0 { return -1 }
var mid = S.count / 2
var start = 0
var end = S.count - 1
while start < mid {
if S[start] != S[end] {
return -1
}
start += 1
end -= 1
}
return mid
}
스코어 57
첨자를 문자열 익스텐션으로 만들고 단순 비교로 for문을 돌렸더니 대용량 데이터에서 타임아웃 에러가 났다.
import Foundation
import Glibc
// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")
public func solution(_ E : inout String, _ L : inout String) -> Int {
func calculateToMin(_ time: String) -> Int {
// compactMap이어야 옵셔널 처리를 안해줄 수 있음
let value = time.components(separatedBy: ":").compactMap { Int($0) }
return value[0] * 60 + value[1]
}
// 입장료 + 첫 한시간까지
var cost = 2 + 3
// 퇴장에서 입장시간과 첫 한시간 빼기
let duration = calculateToMin(L) - calculateToMin(E) - 60
// 올림
if duration > 0 {
cost += Int(ceil((Double(duration) / 60.0))) * 4
}
return cost
}
import Foundation
import Glibc
// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")
public func solution(_ S : inout String) -> String {
// write your code in Swift 4.2.1 (Linux)
var result = ""
for item in S {
if result.last == item {
_ = result.popLast()
} else {
result.append(item)
}
}
return result
}
배열은 removeLast()
나popLast()
를 이용해 제거할 수 있다. 둘은 동일하게 동작하지만 pop의 경우 배열이 비었을 때 사용하면 nil을 반환한다. 문자열은 캐릭터의 배열 형태이므로 append
나 popLast
메서드를 사용할 수 있다.
위 문제는 스택 특징을 이용해 풀었기 때문에 pop 메서드를 이용했다. 이전 문자와 현재 문자가 동일할 경우 이전문자를 없앤다.
import Foundation
import Glibc
import extratypes // this library contains declarations of types from the task
// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")
private func getHeight(_ T: Tree?) -> Int {
if let T = T {
if T.l == nil && T.r == nil {
return 0
}
else if T.l == nil {
return 1 + getHeight(T.r)
}
else if T.r == nil {
return 1 + getHeight(T.l)
}
else {
return 1 + max(getHeight(T.l), getHeight(T.r))
}
} else { return 0 }
}
public func solution(_ T : Tree?) -> Int {
// write your code in Swift 4.2.1 (Linux)
return getHeight(T)
}
재귀함수로 해결
import Foundation
import Glibc
// you can write to stdout for debugging purposes, e.g.
// print("this is a debug message")
public func solution(_ A : inout [Int]) -> Int {
// write your code in Swift 4.2.1 (Linux)
let count = A.count
var inversion = 0
for i in 0..<count {
let first = A[i]
for j in i..<count {
if first > A[j] {
inversion += 1
}
}
if inversion >= 1000000000 {
return -1
}
}
return inversion
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.