有效的java,Find Minimum in Rotated Sorted Array leetcode java

 2023-10-07 阅读 29 评论 0

摘要:?題目:有效的java。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. java in,You may assume no duplicate exists in the array.?解題思路:java

?題目:

有效的java。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.

java in,You may assume no duplicate exists in the array.

?

解題思路:

java instanceof,首先假設一個sorted沒有rotated的數組[1,2,3],假設我們通過一個pivot把這個數組rotate,那么結果可能為:[2,3,1], [3,1,2], 可以發現:num[low]永遠大于(或等于)num[high]。因為你之前是sorted的數組,你在一個sorted的數組找了一個pivot進行rotate,那么比如pivot后面的值都大于pivot之前的值。所以依據這個發現,以及二分法查找。我們可以根據以下判斷來解題。num[mid]有兩種可能性,如果num[mid] > num[high],證明num[mid]在rotated后的那個區間內,這個區間我們剛才已知都大于pivot之前的值,所以最小值就在low=mid+1那個區間內。另一種可能,num[mid] <= num[high],那么我們剛才可以看出來這種可能性說明mid~high以及是排好序的,那么最小值在high=mid這個區間內(mid可能是最小值)。依據此判斷可以找到最小值。

?

?

java search.addfilteror、?

代碼如下:

?1?????public?int?findMin(int[]?num)?{
?2?????????int?low?=?0,?high?=?num.length?-?1;
?3?????????while?(low?<?high?&&?num[low]?>=?num[high])?{
?4?????????????int?mid?=?(low?+?high)?/?2;
?5?????????????if?(num[mid]?>?num[high])
?6?????????????????low?=?mid?+?1;
?7?????????????else
?8?????????????????high?=?mid;
?9?????????}
10?????????return?num[low];
11?????}

?

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/123596.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息