Skip to content

[BinarySearch/UnionFind] leetcode/inudev5.kt #1076

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
28 changes: 28 additions & 0 deletions LeetCode/Binary_Search/Find K-th Smallest Pair Distance/inudev5.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
fun smallestDistancePair(nums: IntArray, k: Int): Int {
//pick two regardlesss of order
val n = nums.size

fun count(dist:Int, k:Int):Boolean{ //using two pointer two count number of valid distances
var (l,r,count) = listOf(0,0,0)
while(l<n){
while(r<n && nums[r]-nums[l]<=dist)r++
count+= r-l-1
l++
}
return count>=k
}
nums.sort()

var l = 0
var r = nums[n-1]-nums[0]

while(l<r){
val mid=l+(r-l)/2
//k개 이상임
if(count(mid,k)) r=mid
else l=mid+1
}
return l
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution {
fun findKthNumber(m: Int, n: Int, k: Int): Int {
//k번째 작은수
// mat[i][j] = (i+1)*(j+1)
var l = 1
var r = m*n
fun count(x:Int,k:Int):Boolean{ //if x has k or more values less than it
var count=0
for(i in 1..m)count+= minOf(x/i,n) //col에서 가능한 count
return count>=k
}
while(l<r){
val mid = l+(r-l)/2
if(count(mid,k)) r=mid
else l=mid+1
}
return l

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
class Solution {
fun maxValue(events: Array<IntArray>, k: Int): Int {

events.sortBy{it[0]}//시작일,종료일로 정렬
val n = events.size
// val lastDay=events[n-1][1]
val dp = Array(n+1){IntArray(k+1)}
fun upperBound(events:Array<IntArray>, start:Int, target:Int):Int{
var l=start
var r= events.size
while(l<r){
val mid = l+(r-l)/2
if(events[mid][0]<=target)l=mid+1
else r=mid
}
return r
}
for(i in n-1 downTo 0){
val next = upperBound(events,i+1,events[i][1])
for(j in 1..k)dp[i][j] = maxOf(dp[i+1][j], events[i][2]+dp[next][j-1])
}
return dp[0][k]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution {
//top-down memoization
fun maxValue(events: Array<IntArray>, k: Int): Int {
//(시작 ,종료,보상) 종료일+1부터 다음 이벤트
//k개를 골랐을 때 maxSum
// var r = events.sumOf{it[2]}
events.sortBy{it[0]}//시작일로 정렬(이분탐색 대상이 시작일이기 때문)
val n = events.size
// val lastDay=events[n-1][1]
val dp = Array(n+1){IntArray(k+1){-1}}
fun upperBound(events:Array<IntArray>, start:Int, target:Int):Int{
var l=start
var r= events.size
while(l<r){
val mid = l+(r-l)/2 //l+(r-l+1)/2는 TLE가 난다. 2개 남았을 때를 생각하면됨
if(events[mid][0]<=target)l=mid+1
else r=mid
}
return r
}
fun solve(idx:Int, k:Int):Int{
if(idx>=n || k==0)return 0
if(dp[idx][k]!=-1)return dp[idx][k]
val next = upperBound(events,idx+1,events[idx][1])
dp[idx][k] = maxOf(solve(idx+1,k), events[idx][2]+solve(next,k-1))
return dp[idx][k]
}

return solve(0,k)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class Solution {
//solution using binary search
fun shortestDistanceColor(colors: IntArray, queries: Array<IntArray>): List<Int> {
val map = hashMapOf<Int,MutableList<Int>>()
for(i in colors.indices){
map.putIfAbsent(colors[i], mutableListOf<Int>())
map[colors[i]]!!.add(i)
}
val res = mutableListOf<Int>()
fun lowerBound(arr:MutableList<Int>, target:Int):Int{
var l=0
var r=arr.size
while(l<r){
val mid= l+(r-l)/2
when{
arr[mid]>=target -> r=mid
else -> l=mid+1
}
}
return l
}
for((idx,color) in queries){
if(color !in map){res.add(-1);continue}
val idxList = map[color]!!
val pos = lowerBound(idxList,idx) //idx 이상인 최소 인덱스
when{
pos==idxList.size -> res.add(idx-idxList[idxList.lastIndex])
pos==0 -> res.add(idxList[0]-idx)
else-> {
val left = idx-idxList[pos-1]
val right = idxList[pos]-idx
res.add(minOf(left,right))
}
}
}

return res
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
class Solution {
class UnionFind(size:Int){
val root:IntArray by lazy { IntArray(size){it} }


fun union(x:Int, y:Int):Boolean{
val rootX = find(x)
val rootY = find(y)
if(rootX!=rootY){
when{
rootX>rootY -> root[rootX] = rootY
rootX<rootY -> root[rootY] = rootX
}
return true
}
return false
}
fun find(x:Int):Int{
if(x==root[x])return x
root[x] = find(root[x])
return root[x]
val set = hashSetOf(intArrayOf(1,2,3,4))

}

}

fun smallestEquivalentString(s1: String, s2: String, baseStr: String): String {
val n = s1.length
val unionfind = UnionFind(26)
for(i in 0..n-1){
unionfind.union(s1[i]-'a', s2[i]-'a')
}
var res = ""
for(i in baseStr.indices){
val num = unionfind.find(baseStr[i]-'a')
res += (num+'a'.toInt()).toChar()
}
return res
}
}
51 changes: 51 additions & 0 deletions LeetCode/Union_Find/Sentent Similarity 2/inudev5.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
class Solution {
class UnionFind(sentence:List<List<String>>){

val root:HashMap<String, String> by lazy {
val map =hashMapOf<String,String>()
for((a,b) in sentence){map.putIfAbsent(a,a);map.putIfAbsent(b,b)}
map
}
val rank:HashMap<String, Int> by lazy {
val map =hashMapOf<String, Int>()
root.keys.forEach{key-> map.put(key,1)}
map
}

//node가 String인 경우


fun union(x:String, y:String):Boolean{
val rootX = find(x)
val rootY = find(y)
if(rootX!=rootY){
when{
rank[rootX]!!>rank[rootY]!! -> root[rootY] = rootX
rank[rootX]!!<rank[rootY]!! -> root[rootX] = rootY
else->{
root[rootX] = rootY
rank.put(rootY, rank.getOrDefault(rootY,1)+1)
}
}
return true
}
return false
}
fun find(word:String):String{
if(word==root[word])return word
root[word] = find(root.getValue(word))
return root.getValue(word)
}
}
fun areSentencesSimilarTwo(sentence1: Array<String>, sentence2: Array<String>, similarPairs: List<List<String>>): Boolean {
if(sentence1.size!=sentence2.size)return false
val unionfind = UnionFind(similarPairs)
for((a,b) in similarPairs)unionfind.union(a,b)
for(i in sentence1.indices){
if(sentence1[i]==sentence2[i])continue
if(unionfind.root[sentence1[i]]==null ||unionfind.root[sentence2[i]]==null) return false
if(unionfind.find(sentence1[i])!=unionfind.find(sentence2[i]))return false
}
return true
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
class Solution {
class UnionFind(size:Int){
val root:IntArray by lazy { IntArray(size){it} }
val rank:IntArray by lazy { IntArray(size){1} }

fun union(x:Int, y:Int):Boolean{
val rootX = find(x)
val rootY = find(y)
if(rootX!=rootY){
when{
rank[rootX]>rank[rootY] -> root[rootY] = rootX
rank[rootX]<rank[rootY]-> root[rootX]= rootY
else->{
root[rootY]= rootX
rank[rootX]+=1
}
}
return true
}
return false
}
fun find(x:Int):Int{
if(x==root[x])return x
root[x] = find(root[x])
return root[x]
}
}
fun earliestAcq(logs: Array<IntArray>, n: Int): Int {
val uf=UnionFind(n)
var prestamp = 0
var count=n
logs.sortBy({it[0]})
for((timestamp,a,b) in logs){
if(uf.union(a,b))count-=1
if(count==1)return timestamp
}
return -1
}
}