본문 바로가기
코딩테스트

[kotlin] leetcode - Search Insert Position

by 얘리밍 2022. 4. 27.
320x100
728x90

35. Search Insert Position : https://leetcode.com/problems/search-insert-position/

 

Search Insert Position - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

이진탐색 활용

class Solution {
    fun searchInsert(nums: IntArray, target: Int): Int {
        var low = 0;
        var high = nums.lastIndex;
        
        while(low<=high){
            var mid = (low + high)/2;
            when{
                target == nums[mid] -> return mid
                target > nums[mid] -> low = mid + 1
                else -> high = mid - 1
            } 
        }
        return low
    }
}
Runtime: 204 ms, faster than 75.11% of Kotlin online submissions for Search Insert Position.
Memory Usage: 37.7 MB, less than 65.80% of Kotlin online submissions for Search Insert Position.
728x90
반응형