> For the complete documentation index, see [llms.txt](https://junnie.gitbook.io/nine-chapter/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://junnie.gitbook.io/nine-chapter/1.binary-search/159find-minimum-in-rotated-sorted-array.md).

# 159.Find Minimum in Rotated Sorted Array

## 1.Description(Medium)

Suppose a sorted array 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`).

Find the minimum element.

### Notice

You may assume no duplicate exists in the array.

**Example**

Given`[4, 5, 6, 7, 0, 1, 2]`return`0`

## 2.Code

注意这个题和一般的BS相反

找first position <=target(target 设置为最后一个数)

nums\[mid]\<target 向前找

nums\[mid]>target 向后找

nums\[mid]==target 向前找

注意最后肯定会返回一个值，所以直接else返回就行了。

```
public int findMin(int[] num) {
       if(num==null || num.length==0){
            return -1;
        }

        int start=0,end=num.length-1;
        int target=num[num.length-1];//set last number as the target,find first element<=target

        //find first element<=target
        while(start+1<end){
            int mid=start+(end-start)/2;

            if(num[mid]==target){
                end=mid;                
            }
            else if(num[mid]>target){
                start=mid;
            }
            else{
                end=mid;
            }
        }

        if(num[start]<=target){
            return num[start];
        }
        else{
            return num[end];
        }
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://junnie.gitbook.io/nine-chapter/1.binary-search/159find-minimum-in-rotated-sorted-array.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
