LeetCode Search in Rotated Sorted Array II
2015-11-11 22:17
477 查看
Description:
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.
Solution:
The solution is very similar to the former one, the only difference is that we need to differentiate the condition that nums[l] == nums[mid] and nums[r] == nums[mid], which requires that we need to l++ and r-- respectively.
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.
Solution:
The solution is very similar to the former one, the only difference is that we need to differentiate the condition that nums[l] == nums[mid] and nums[r] == nums[mid], which requires that we need to l++ and r-- respectively.
<span style="font-size:18px;">import java.util.*; public class Solution { public boolean search(int[] nums, int target) { if (nums == null) return false; int n = nums.length; if (n == 0) return false; int l = 0, r = n - 1, mid; while (l <= r) { mid = (l + r) / 2; if (nums[mid] == target) return true; if (nums[l] < nums[mid]) { if (nums[l] <= target && target < nums[mid]) { r = mid - 1; } else { l = mid + 1; } } else if (nums[mid] < nums[r]) { if (nums[mid] < target && target <= nums[r]) { l = mid + 1; } else { r = mid - 1; } } else if (nums[l] == nums[mid]) { l++; } else { r--; } } return false; } }</span>
相关文章推荐
- PHP - 拒绝低版本PHP
- 图像灰度化方法总结及其VC实现
- 浅谈Hybrid技术的设计与实现
- [多浏览器兼容]IE浏览器HTML条件注释
- ps2015安装guideguide参考线辅助工具
- Mac下Python与Mysql链接
- 转载:Eclipse build Android时不生成apk问题解决方法
- Java编程思想学习笔记——枚举类型
- nyoj Yougth的最大化 914 (二分搜索)
- ajax知识点
- Python第三课
- linux 批量 替换 namespace缩进
- UVA 10048 Audiophobia(Floyd算法)
- 深度学习概述:从感知机到深度网络
- OnClickListener接口简介
- #define GPFCON (* (volatile unsigned long * )0x56000050 )
- 浅谈WebLogic和Tomcat
- 检查数组的方法
- NYOJ 202 红黑树 【二叉树 中序遍历】
- Tomcat安装配置