美文网首页
LeetCode之Search in Rotated Sorte

LeetCode之Search in Rotated Sorte

作者: 糕冷羊 | 来源:发表于2021-10-08 17:26 被阅读0次

问题:



方法:
题目中复杂度要求为O(logn),所以使用变种二分查找,要根据值的大小重置二分区间。

package com.eric.leetcode

class SearchInRotatedSortedArray {
    fun search(nums: IntArray, target: Int): Int {
        var start = 0
        var end = nums.lastIndex
        while (start <= end) {
            val pivot = (start + end) / 2
            if (nums[pivot] == target) {
                return pivot
            } else if (nums[start] <= nums[pivot]) {
                if (target <= nums[pivot] && target >= nums[start]) {
                    end = pivot - 1
                } else {
                    start = pivot + 1
                }
            } else {
                if (target >= nums[pivot] && target <= nums[end]) {
                    start = pivot + 1
                } else {
                    end = pivot - 1
                }
            }
        }
        return -1
    }
}

fun main() {
    val input = intArrayOf(4, 5, 6, 7, 8, 1, 2, 3)
    val searchInRotatedSortedArray = SearchInRotatedSortedArray()
    searchInRotatedSortedArray.search(input, 8)
}

有问题随时沟通

具体代码实现可以参考Github

相关文章

网友评论

      本文标题:LeetCode之Search in Rotated Sorte

      本文链接:https://www.haomeiwen.com/subject/tzvxoltx.html