2019.6.15 #程序员笔试必备# LeetCode 从零单刷个人笔记整理(持续更新)
github:https://github.com/ChopinXBP/LeetCode-Babel
题目要求O(log n),很明显需要用二分查找来做。不过分类逻辑却需要思考一下。
每次对半截断后,数组可能有两种情况,一种是包含翻转分界的子数组(头元素大于尾元素),另一种是正常升序的数组。在翻转数组中,又分为target位于翻转边界前和位于翻转边界后两种情况。分类完成后,按照正常的二分算法处理即可。
在寻找最小值的升级版题目中,由于可能会出现重复元素,导致无法判断区间,例如[1,0,1,1,1]和[1,1,1,0,1],可以采用end–来规避问题。
Suppose an array sorted in ascending order 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]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm’s runtime complexity must be in the order of O(log n).
假设按照升序排序的数组在预先未知的某个点上进行了旋转。
( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
你可以假设数组中不存在重复的元素。
你的算法时间复杂度必须是 O(log n) 级别。
示例 1:
输入: nums = [4,5,6,7,0,1,2], target = 0
输出: 4
示例 2:
输入: nums = [4,5,6,7,0,1,2], target = 3
输出: -1
/**
*
* @author ChopinXBP
* Suppose an array sorted in ascending order 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]).
* You are given a target value to search. If found in the array return its index, otherwise return -1.
* You may assume no duplicate exists in the array.
* Your algorithm's runtime complexity must be in the order of O(log n).
* 假设按照升序排序的数组在预先未知的某个点上进行了旋转。
* ( 例如,数组 [0,1,2,4,5,6,7] 可能变为 [4,5,6,7,0,1,2] )。
* 搜索一个给定的目标值,如果数组中存在这个目标值,则返回它的索引,否则返回 -1 。
* 你可以假设数组中不存在重复的元素。
* 你的算法时间复杂度必须是 O(log n) 级别。
*
*/
public class SearchinRotatedSortedArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public int search(int[] nums, int target) {
if(nums == null || nums.length == 0)return -1;
int begin = 0;