Find minimum value in rotated sorted array
Topic description: Given an array of length n, it is prearranged in ascending order, and after 1 to n rotations, the input array is obtained. For example, the original array nums = [0,1,2,4,5,6,7] may get:
- If you rotate 4 times, you can get [4,5,6,7,0,1,2]
- If you rotate 7 times, you can get [0,1,2,4,5,6,7]
Note that the result of one rotation of the array [a[0], a[1], a[2], ..., a[n-1]] is the array [a[n-1], a[0], a [1], a[2], ..., a[n-2]] .You are given an array nums with different element values, which turns out to be an array in ascending order, rotated multiple times as described above. Please find and return the smallest element in the array.
For example descriptions, please refer to the official website of LeetCode.
Source: LeetCode
Link: https://leetcode-cn.com/problems/find-minimum-in-rotated-sorted-array/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.
Solution 1: Array Traversal
By traversing the array to solve, the traversal process is as follows:
- If the current element is greater than the next element of the current element, it means that the current element is the maximum value of the original array, and the next element is the minimum value, and the next element is returned directly.
If it is found that there is no next element whose current element is greater than the current element after traversing, it means that the first element is the smallest element, and it is returned.
public class LeetCode_153 {
public static int findMin(int[] nums) {
// 遍历数组中的元素,如果当前元素大于当前元素的下一个元素,则说明当前元素是原始数组的最大值,而下一个元素即是最小值
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] > nums[i + 1]) {
return nums[i + 1];
}
}
// 如果不存在当前元素大于当前元素的下一个元素,则说明第一个元素是最小元素,返回之
return nums[0];
}
public static void main(String[] args) {
int[] nums = new int[]{4, 5, 6, 7, 0, 1, 2};
// 测试用例,期望输出: 0
System.out.println(findMin(nums));
}
}
[Daily Message] Life is like this, without tempering, without exercise, you will not grow.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。