Jan 23 - Search In Rotated Array II; Array; Binary Search;
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jan 23 - Search In Rotated Array II; Array; Binary Search;相关的知识,希望对你有一定的参考价值。
public class Solution { public boolean search(int[] nums, int target) { int len = nums.length; if(len == 0) return false; int low = 0; int high = len-1; while(low < high){ int mid = (low+high)/2; // do not concern the integer overrange situation if(nums[mid] == target) return true; if(nums[mid] < nums[high] || nums[mid] < nums[low]){ if(target > nums[mid] && target <= nums[high]) low = mid + 1; else high = mid - 1; } else if(nums[mid] > nums[low] || nums[mid] > nums[high]){ if(target < nums[mid] && target >= nums[low]) high = mid - 1; else low = mid + 1; } else high--; } if(nums[low] == target) return true; return false; } }
Initially low = 0, high = len-1; the condition of while loop is low < high; mid = (low+high)/2;
if nums[mid] == target, sure we find the value same as the target, return true. If not,
We analyze three cases:
1. right part from mid to high sorted, and left part from low to mid unsorted. (nums[mid] < nums[high] || nums[mid] < nums[low])
Then we compare the target with some specific value to detemine which part the target should be in if its in the array.
if(target > nums[mid] && target <= nums[high]) target should be in the right part, set low = mid +1;
otherwise the target should be in the left part, high = mid - 1;
2. left part is sorted. (nums[mid] > nums[low] || nums[mid] > nums[high])
Similarly, if(target< nums[mid] && target >= nums[low]) high = mid -1;
otherwise, the target should be in the right part, low = mid + 1;
3. The last possibility is that nums[low] == nums[mid] == nums[high], in this case, just let high--; to reduce the duplication occurance.
以上是关于Jan 23 - Search In Rotated Array II; Array; Binary Search;的主要内容,如果未能解决你的问题,请参考以下文章
Jan 23 - Decode Ways; DP; Array;
Jan 23 - Gray Code; BackTracking;
Jan 27 - Valid Binary Search Tree; DFS;
Jan 26 - Unique Binary Search Trees; DP; Trees; Recursion & Iteration;