LintCode:搜索旋转排序数组
来源:互联网 发布:58网络销售怎么样 编辑:程序博客网 时间:2024/06/07 19:58
假设有一个排序的按未知的旋转轴旋转的数组(比如,0 1 2 4 5 6 7 可能成为4 5 6 7 0 1 2)。给定一个目标值进行搜索,如果在数组中找到目标值返回数组中的索引位置,否则返回-1。
你可以假设数组中不存在重复的元素。
您在真实的面试中是否遇到过这个题? Yes
样例
标签 Expand 给出[4, 5, 1, 2, 3]和target=1,返回 2
给出[4, 5, 1, 2, 3]和target=0,返回 -1
相关题目 Expand
解题思路:
2分搜索
http://www.code123.cc/docs/leetcode-notes/binary_search/search_in_rotated_sorted_array.html
notes/binary_search/search_in_rotated_sorted_array.html
public class Solution { /** *@param A : an integer rotated sorted array *@param target : an integer to be searched *return : an integer */ public int search(int[] A, int target) { // write your code here if (A == null || 0 == A.length) return -1; int left = 0; int right = A.length - 1; int mid = -1; while (left < right - 1) { mid = (left + right) / 2; if (target == A[mid]) { return mid; } if (A[left] < A[mid]) { if (A[left] <= target && A[mid] >= target) { right = mid; } else { left = mid; } } else { if (A[mid] <= target && A[right] >= target ) { left = mid; } else { right = mid; } } } if (target == A[left]) { return left; } else if (target == A[right]) { return right; } else { return -1; } }}
0 0
- LintCode-搜索旋转排序数组
- LintCode : 搜索旋转排序数组
- LintCode:搜索旋转排序数组
- LintCode:搜索旋转排序数组
- *[Lintcode]搜索旋转排序数组
- lintcode,搜索旋转排序数组
- Lintcode 搜索旋转排序数组
- lintcode--搜索旋转排序数组
- LintCode-搜索旋转排序数组 II
- lintcode-搜索旋转排序数组-62
- LintCode : 搜索旋转排序数组 II
- lintcode-搜索旋转排序数组II-63
- LintCode:搜索旋转排序数组 II
- LintCode 62 搜索旋转排序数组
- Lintcode 搜索旋转排序数组 II
- LintCode 62 搜索旋转排序数组
- LintCode 63 搜索旋转排序数组 II
- LintCode:M-搜索旋转排序数组
- Git提交远程分支任务
- hadoop datanode 打不开
- 飞花的鱼塘
- 手动安装liberty版本openstack环境(allinone)---安装数据库及rabbitmq
- Mina框架的使用
- LintCode:搜索旋转排序数组
- Struts2中如何使用session、request等对象
- 微信支付--网页版-V3-(1)
- 命令行调用编译器
- 字符的变化
- 关于“除数和余数的最大公约数就是被除数和除数的最大公约数”
- LintCode:搜索旋转排序数组 II
- 函数与程序结构
- 数组初始化