Test instructions: Finding the smallest element from a translated array
Idea 1: The simplest idea is to sort and then take the first element, the complexity O (N*log (N))
Code Listing 1:
public class Solution {public int findmin (int[] num) { arrays.sort (num); return num[0];} }
Idea 2: Traverse, compare the first of the two orderby ordinal numbers, 4 5 6 7 0 1 2 complexity O (N)
Code Listing 2:
public int findmin (int[] num) {//solution 1 times int min = num[0], currmin = num[0]; int i = 0; while (+ + i < num.length) { currmin = math.min (num[i],currmin); if (i + 1 < num.length && Num[i + 1] < Currmin) { currmin = num[i + 1]; break; } } min = math.min (min, currmin); return min; }
Train of thought 3: dichotomy, Time complexity O (log (N))
4 5 670 1 2 mid > R//l= mid +1
4 5 601 2 3 Mid < R//R = Mid
Code:
public int findmin (int[] num) {//solution 32 min int min = 0; int L = 0, R = num.length-1, mid; while (L < R) { mid = L + (r-l)/2; if (Num[mid] > Num[r]) { L = mid + 1; } else { r = Mid; } } min = num[l]; return min; }
[Leetcode] Find Minimum in rotated Sorted Array