- Search in Rotated Sorted Array
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).
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0
Output: 4
Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3
Output: -1
题目解析:
二分查找,用于快速寻找有序数值中特定数值得经典解法,性能优秀。此题对有序数组进行了旋转,导致有序数组分成了二个有序数组,此时按照二分查找得方法,对其进行循环,同样能解决问题,这是题目解题思路。
代码:
class Solution {
public int search(int[] nums, int target) {
int left = 0;
int right = nums.length -1;
if(nums.length == 0)//长度为0,直接返回 -1
{
return -1;
}
while(left <= right)//循环二分查找
{
int mid = left + (right - left) / 2;//取初次中间数值
if(nums[mid] == target)//等于中间数值,立即返回当前值
{
return mid;
}
if (nums[left] < nums[mid])//中间值 大于 最左端(初次)
{
if (target > nums[mid] || target < nums[left])
//目标值大于初次中间值或者目标值小于初次最左端数值,表明目标值在右侧
{
left = mid + 1;//左侧哨兵移动至mid右侧第一位
}
else
{
right = mid - 1;//反之亦然
}
}
else if (nums[left] > nums[mid]) //中间值 小于 最左端(初次)
{
if (target < nums[mid] || target > nums[right])
//目标值小于初次中间值或者目标值大于初次最右端数值,表面目标值在左侧
{
right = mid - 1;//右侧哨兵移动至mid左侧第一位
}
else
{
left = mid + 1;//反之亦然
}
}
else // 中间值 等于 最左端(初次)
{
left += 1;
}
//如此循环找到target下标位置
}
return -1;//未找到返回-1
}
}
性能:
总结
1.算法题目和 语言没太大关系,关键还是得看思路,我之前都是用C++,现在使用Java,没多少区别;
2.算法题得多多练习,从单个实例,抽象出通用方法,需要不断积累,和大家以此共勉。