Skip to content

Latest commit

 

History

History
112 lines (93 loc) · 2.59 KB

33.搜索旋转排序数组.md

File metadata and controls

112 lines (93 loc) · 2.59 KB

33. 搜索旋转排序数组

url

题目

整数数组 nums 按升序排列,数组中的值 互不相同 。

在传递给函数之前,nums 在预先未知的某个下标 k(0 <= k < nums.length)上进行了 旋转,使数组变为 [nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]](下标 从 0 开始 计数)。例如, [0,1,2,4,5,6,7] 在下标 3 处经旋转后可能变为 [4,5,6,7,0,1,2] 。

给你 旋转后 的数组 nums 和一个整数 target ,如果 nums 中存在这个目标值 target ,则返回它的索引,否则返回 -1 。

输入:nums = [4,5,6,7,0,1,2], target = 0
输出:4
输入:nums = [4,5,6,7,0,1,2], target = 3
输出:-1
输入:nums = [1], target = 0
输出:-1

方法

code

js

let search = (nums, target) => {
    if (nums === null || nums.length === 0)
        return -1;
    let l = 0, r = nums.length - 1;
    while (l <= r) {
        let m = l + Math.floor((r - l) / 2);
        if (nums[m] === target)
            return m;
        else if (nums[m] < nums[r]){
            if (nums[m] < target && target <= nums[r])
                l = m + 1;
            else
                r = m - 1;
        } else {
            if (nums[l] <= target && target < nums[m])
                r = m - 1;
            else
                l = m + 1;
        }
    }
    return -1;
};

go

func search2(nums []int, target int) int {
	l := len(nums)
	left, right := 0, l - 1
	for left <= right {
		m := (left + right) / 2
		if nums[m] == target {
			return m
		} else if nums[m] < nums[right] {
			if nums[m] < target && target <= nums[right] {
				left = m + 1
			} else {
				right = m - 1
			}
		} else {
			if nums[left] <= target && target < nums[m] {
				right = m - 1
			} else {
				left = m + 1
			}
		}
	}
	return -1
}

java

class Solution {
    public int search(int[] nums, int target) {
        int len = nums.length;
        int left = 0, right = len - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (nums[mid] == target)
                return mid;
            else if(nums[mid] < nums[right]) {
                if (nums[mid] < target && target <= nums[right])
                    left = mid + 1;
                else 
                    right = mid - 1;
            } else {
                if (nums[left] <= target && target < nums[mid])
                    right = mid - 1;
                else 
                    left = mid + 1;
            }
        }
        return - 1;
    }
}