81. Search in Rotated Sorted Array II
2016-02-22 04:53
302 查看
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 1 Binary search
public static boolean search(int[] nums, int target) {
int start = 0, end = nums.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target)
return true; // return mid in Search in Rotated Array I
if (nums[mid] > nums[start]) { // left half is sorted
if (target >= nums [start] && target < nums[mid])
end = mid - 1;
else
start = mid + 1;
} else if (nums[mid] < nums[start]) { // right half is sorted
if (target > nums[mid] && target <= nums[end])
start = mid + 1;
else
end = mid - 1;
} else
start++;
}
return false;
}
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 1 Binary search
public static boolean search(int[] nums, int target) {
int start = 0, end = nums.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (nums[mid] == target)
return true; // return mid in Search in Rotated Array I
if (nums[mid] > nums[start]) { // left half is sorted
if (target >= nums [start] && target < nums[mid])
end = mid - 1;
else
start = mid + 1;
} else if (nums[mid] < nums[start]) { // right half is sorted
if (target > nums[mid] && target <= nums[end])
start = mid + 1;
else
end = mid - 1;
} else
start++;
}
return false;
}
相关文章推荐
- 51Nod 1013 3的幂的和(快速幂+逆元)
- LeetCode Binary Tree Upside Down
- 【Leetcode】House Robber II
- [Immutable.js] Converting Immutable.js Structures to Javascript and other Immutable Types
- Linux发展史
- 怎样的学术导师是好导师(Nature)
- 【Android】11.6 Fragments基本用法示例
- 【NYOJ】[268]荷兰国旗问题
- [Immutable.js] Transforming Immutable Data with Reduce
- 【Android】11.5 创建和管理Fragments
- 按首字母分类并排序显示的列表(二)--给BaseExpandableListAdapter提供数据的HashList
- 【Android】11.4 Fragment及其生命周期
- uva 10277 Boastin' Red Socks
- Java Integer.highestOneBit(i)代码品读
- LeetCode Binary Search Tree Iterator
- 矩阵分解的推荐算法入门-好好看
- 树的重心——树形dp
- matlab练习程序(非负矩阵分解)
- 关于APUE第十六章的客户端程序返回Servname not supported for ai_socktype错误的解决方法
- 【基础技术】Java基础那些事儿系列-cmd和command