81. Search in Rotated Sorted Array II

网友投稿 619 2022-09-04

81. Search in Rotated Sorted Array II

81. Search in Rotated Sorted Array II

Follow up for "Search in Rotated Sorted Array":What if duplicates are allowed?Would this affect the run-time complexity? How and why?

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Write a function to determine if a given target is in the array.

The array may contain duplicates.

class Solution { public boolean search(int[] nums, int target) { int left = 0, right = nums.length - 1; while (left <= right) { int mid = (left + right) / 2; if (target == nums[mid]) return true; if (nums[mid] == nums[left]) left++; else if (nums[mid] > nums[left]) { if (nums[left] <= target && nums[mid] > target) right = mid - 1; else left = mid + 1; } else { if (nums[mid] < target && target <= nums[right]) left = mid + 1; else right = mid - 1; } } return false; }}

class Solution { public boolean search(int[] nums, int target) { for (int n : nums) { if (n == target) return true; } return false; }}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:628. Maximum Product of Three Numbers
下一篇:php7.4重量级特性:预加载(php方法重载)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~