题目:
把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。 输入一个非减排序的数组的一个旋转,输出旋转数组的最小元素。 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。 NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
二分法
public class SearchTarInRotateList {
public static void main(String[] args) {
int[] arr = {15,16,19,20,25,1,3,5,7,10,14};
int res = findMinValueIndex(arr);
System.out.println(res);
}
private static int findMinValueIndex(int[] arr) {
int s = 0;
int e = arr.length - 1;
while (s + 1 < e) {
int mid = (s +e) / 2;
if (arr[mid] > arr[e]) {
s = mid;
} else {
e = mid;
}
}
int resIndex = arr[s] > arr[e] ? e : s;
return Arrays.stream(arr).boxed().collect(Collectors.toList()).get(resIndex);
}
}
我们现在主要来研究数组的旋转,集合的旋转,或链表的旋转:
1.场景:
输入数组{1,2,3,4,5,6}从第4位开始旋转即旋转后面两个数,得到的新数组为:{5,6,1,2,3,4};
集合同理
链表:1 -> 2 -> 3 -> 4 ->5 ,k=2,从后向前旋转两个,4 -> 5 -> 1 -> 2 -> 3
2.API方法:
这里引入集合工具类Collections.rotate(Collection<?> list ,int distance)方法:
其中,list表示要被旋转的集合,distance表示旋转元素的个数
3.使用:
1.distance > 0,表示从后向前旋转,旋转distance个元素
即:{1,2,3,4,5,6},distance=2,则旋转后的集合为{5,6,1,2,3,4}
2.distance < 0,表示从前向后旋转,旋转||distance||个元素
即:{1,2,3,4,5,6},distance= -2,则旋转后的集合为{3,4,5,6,1,2}