Skip to content
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

LeetCode-33. Search in Rotated Sorted Array #49

Closed
ninehills opened this issue Aug 8, 2017 · 1 comment
Closed

LeetCode-33. Search in Rotated Sorted Array #49

ninehills opened this issue Aug 8, 2017 · 1 comment
Labels

Comments

@ninehills
Copy link
Owner

ninehills commented Aug 8, 2017

问题

https://leetcode.com/problems/search-in-rotated-sorted-array/description/
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

You are given a target value to search. If found in the array return its index, otherwise return -1.

You may assume no duplicate exists in the array.

思路

  • 顺序查找就不说了,最优解应该是二分查找的一个变种,主要是考虑边界条件

解答

package main

import "fmt"

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

// ----------------------

func main() {
	fmt.Println(search([]int{1, 3}, 0))
	fmt.Println(search([]int{}, 5))
	fmt.Println(search([]int{4, 5, 6, 7, 0, 1, 2}, 1))
	fmt.Println(search([]int{4, 5, 6, 7, 8, 1, 2, 3}, 8))
}
@ninehills
Copy link
Owner Author

#4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant