码迷,mamicode.com
首页 > 编程语言 > 详细

Java for LeetCode 081 Search in Rotated Sorted Array II

时间:2015-05-19 12:24:16      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:

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.

解题思路:

参考Java for LeetCode 033 Search in Rotated Sorted Array 修改下代码即可,JAVA实现如下:

    public boolean search(int[] nums, int target) {
		int left = 0, right = nums.length - 1;
		while (left <= right) {
			if (target == nums[(right + left) / 2])
				return true;
			// 右半部分为旋转区域
			if (nums[(right + left) / 2] > nums[left]) {
				if (target >= nums[left] && target < nums[(right + left) / 2])
					right = (right + left) / 2 - 1;
				else
					left = (right + left) / 2 + 1;
			}
			// 左半部分为旋转区域
			else if (nums[(right + left) / 2] < nums[left]) {
				if (target > nums[(right + left) / 2] && target <= nums[right])
					left = (right + left) / 2 + 1;
				else
					right = (right + left) / 2 - 1;
			} 
			// 老实遍历
			else
				left++;
		}
		return false;
    }

 

Java for LeetCode 081 Search in Rotated Sorted Array II

标签:

原文地址:http://www.cnblogs.com/tonyluis/p/4513940.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!