Find Minimum in Rotated Sorted Array II, rotatedsorted
This question is the extension of Search in Rotated Sorted Array. The idea has been introduced in Find Minimum in Rotated Sorted Array, the only difference between Find Minimum in Rotated Sorted Array and Find Minimum in Rotated Sorted Array is that the elements in this question are duplicated. However, this condition affects the time complexity of the algorithm. It turns out that we rely on the Size relationship between the intermediate and edge elements to determine which half is not affected by rotate and is still ordered. Now, because of the repeated appearance, If we encounter a situation where the center is equal to the edge, we cannot determine which side is ordered, because which side may be ordered. If the original array is {, 3, 3, 3, 3}, it may be {3, 3, 3, 3, 3, 1, 2}, or {3, 1, 2, 3, 3, 3, 3} after rotation, 3}. In this way, we judge that the left and center are both 3. We don't know which half should be cut off. The solution can only be to move the edge step until the edge and the middle are not equal or encounter, which leads to the possibility that the edge cannot be halved. Therefore, in the worst case, each step is moved. The total number of moves is n, and the time complexity of the algorithm is changed to O (n ). The Code is as follows:
public int findMin(int[] num) { if(num == null || num.length==0) return 0; int l = 0; int r = num.length-1; int min = num[0]; while(l<r-1) { int m = (l+r)/2; if(num[l]<num[m]) { min = Math.min(num[l],min); l = m+1; } else if(num[l]>num[m]) { min = Math.min(num[m],min); r = m-1; } else { l++; } } min = Math.min(num[r],min); min = Math.min(num[l],min); return min;}In interviews, this problem is still quite common. The trend is that the interviewer tends to start from a question, and then follow up asks some extended questions, and this question involves a change in complexity, therefore, the interview is indeed a good question, and naturally it is more likely to appear.