Follow up for "Search in Rotated Sorted Array":
What if duplicates are allowed?
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.
假设原数组是{1,2,3,3,3,3,3},那么旋转之后有可能是{3,3,3,3,3,1,2},或者{3,1,2,3,3,3,3},这样的我们判断左边缘和中心的时候都是3,如果我们要寻找1或者2,我们并不知道应该跳向哪一半。解决的办法只能是对边缘移动一步,直到边缘和中间不在相等或者相遇,这就导致了会有不能切去一半的可能。所以最坏情况(比如全部都是一个元素,或者只有一个元素不同于其他元素,而他就在最后一个)就会出现每次移动一步,总共是n步,算法的时间复杂度变成O(n)。
public class Solution { public boolean search(int[] nums, int target) { if (nums == null || nums.length == 0) { return false; } int left = 0; int right = nums.length - 1; while (left <= right) { int mid = (left + right) / 2; if (nums[mid] == target) { return true; } if (nums[mid] > nums[left]) { if (target >= nums[left] && target < nums[mid]) { right = mid - 1; } else { left = mid + 1; } } else if (nums[mid] < nums[left]) { if (target <= nums[right] && target > nums[mid]) { left = mid + 1; } else { right = mid - 1; } } else { left++; } } return false; } }
public class Solution { public boolean search(int[] A, int target) { if (A.length == 0 || A == null){ return false; } int start = 0; int end = A.length - 1; while (start + 1 < end){ int mid = start + (end - start) / 2; // if (A[mid] == target){ // return true; // } if (A[start] == A[mid]){//if start == mid 可能出现mid在第一区也可能第二区 start++;// 所以用start++ 来判断 } else if (A[mid] > A[start]){// case Mid1 if (target >= A[start] && target <= A[mid]){// end = mid; } else { start = mid; } } else if (A[mid] < A[start]) { //case Mid2 if (A[start] > target && A[mid] < target){ start = mid; } else { end = mid; } } else { end--; } } if (A[start] == target){ return true; } else if (A[end] == target){ return true; } else { return false; } } }
没有评论:
发表评论