1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
fun binary_search(arr:List<Int>, find: Int, start: Int, end: Int): Int {
if(start>end) {
return -1
}
val mid = (start+end)/2
if(arr[mid]==find){
return mid
}
else if(arr[mid]>find){
return binary_search(arr,find,start,mid-1)
}
else{
return binary_search(arr,find,mid+1,end)
}
}
fun main(){
val (num , find)= readLine()!!.split(" ").map{it.toInt()}
val arr = readLine()!!.split(" ").map{it.toInt()}
val result = binary_search(arr,find,0,num-1)
if(result==-1)
println("원소가 존재하지 않습니다.")
else{
println(result+1)
}
}
|
cs |
반복문 버전.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
fun binary_search(arr:List<Int>, find: Int, start: Int, end: Int): Int {
var end = end
var start = start
var mid = start + end /2
while(start<=end){
mid = start + end /2
if(arr[mid]==find){
return mid
}
else if(arr[mid]>find){
end = mid-1
}
else{
start = mid+1
}
}
return -1
}
fun main(){
val (num , find)= readLine()!!.split(" ").map{it.toInt()}
val arr = readLine()!!.split(" ").map{it.toInt()}
val result = binary_search(arr,find,0,num-1)
if(result==-1)
println("원소가 존재하지 않습니다.")
else{
println(result+1)
}
}
|
cs |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
fun binary_search(arr:List<Int>, num:Int, find: Int, start: Int, end: Int): Int {
var end = end
var start = start
var mid = (start + end) /2
var total = 0
while(start<=end){
total=0
mid = (start + end) /2
for(i in 0 until num){
if(arr[i]-mid>0)
total+=(arr[i]-mid)
}
//println("start: $start, end: $end, mid: $mid total: $total")
//println(mid)
if(total==find){
return mid
}
else if(total>find){
start = mid+1
}
else{
end = mid-1
}
}
return mid
}
fun main(){
val (num , want)= readLine()!!.split(" ").map{it.toInt()}
val arr = readLine()!!.split(" ").map{it.toInt()}
val end = arr.maxByOrNull { it }!!.toInt()
println(end)
val result = binary_search(arr,num,want,0,end)
println(result)
}
|
cs |
'알고리즘 공부 > 미분류' 카테고리의 다른 글
팰린드롬수 1259번 with Kotlin (0) | 2021.07.10 |
---|---|
좌표정렬하기 11651번 with Kotlin (0) | 2021.07.10 |
백준 11650번 with Kotlin #Pair #sortWith #sortBy (0) | 2021.07.09 |
백준 10814번 with Kotlin #sortWith #정렬 (0) | 2021.07.09 |
백준 1436번 with Kotlin #문자열에 있는 내용 부분적 체크 (0) | 2021.07.09 |