LeetCode Search in Rotated Sorted Array II
2015-07-12 20:57
316 查看
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
题意:给出一个数组(有重复元素,是经过旋转的有序数组)及一个数,问这个数是否在数组中出现
思路:二分法
代码如下
第一种用递归(用时364ms)
第二种非递归(用时388ms)
代码如下
public class Solution {
public boolean search(int[] nums, int target)
{
int left = 0, right = nums.length - 1;
while (left <= right)
{
int mid = (left + right) >> 1;
if (nums[mid] == target) return true;
else if (nums[left] == nums[mid] && nums[mid] == nums[right])
{
left++;
right--;
}
else if (nums[left] <= nums[mid])
{
if (target >= nums[left] && target < nums[mid]) right = mid - 1;
else left = mid + 1;
}
else
{
if (target > nums[mid] && target <= nums[right]) left = mid + 1;
else right = mid - 1;
}
}
return false;
}
}
Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
Would this affect the run-time complexity? How and why?
Write a function to determine if a given target is in the array.
题意:给出一个数组(有重复元素,是经过旋转的有序数组)及一个数,问这个数是否在数组中出现
思路:二分法
代码如下
第一种用递归(用时364ms)
public class Solution { private boolean check(int[] nums, int left, int right, int target) { int mid = (left + right) >> 1; if (left > right) return false; if (nums[mid] == target) return true; return check(nums, left, mid - 1, target) || check(nums, mid + 1, right, target); } public boolean search(int[] nums, int target) { int left = 0, right = nums.length - 1; return check(nums, left, right, target); } }
第二种非递归(用时388ms)
代码如下
public class Solution {
public boolean search(int[] nums, int target)
{
int left = 0, right = nums.length - 1;
while (left <= right)
{
int mid = (left + right) >> 1;
if (nums[mid] == target) return true;
else if (nums[left] == nums[mid] && nums[mid] == nums[right])
{
left++;
right--;
}
else if (nums[left] <= nums[mid])
{
if (target >= nums[left] && target < nums[mid]) right = mid - 1;
else left = mid + 1;
}
else
{
if (target > nums[mid] && target <= nums[right]) left = mid + 1;
else right = mid - 1;
}
}
return false;
}
}
相关文章推荐
- java程序员必知的8大排序
- vmware快捷键
- 安装VMware Workstation 10
- nginx编译安装过程优化
- 设计模式(2) - 抽象工厂
- 跟着实例学习设计模式(6)-生成器模式builder(创建型)
- Unity3D一种打包exe后看不到角色的情况
- 中国大学MOOC-翁恺-C语言程序设计习题集-解答汇总
- android的消息处理机制(图+源码分析)——Looper,Handler,Message (非常棒)
- 张向东:造车十月,我学会的七件事
- Data语意学
- 《活着》读后感
- Linux 查看IP、查看Gateway、查看DNS
- UITableView
- javascript 日期时间函数(经典+完善+实用)
- android--获取视频,图片缩略图的具体实现
- 解决windows防火墙无法启动的问题
- 解决windows防火墙无法启动的问题
- linux 输入输出重定向
- 文件的上传和下载