Last active
March 15, 2016 20:52
-
-
Save cangoal/552092e7868494161912 to your computer and use it in GitHub Desktop.
LeetCode - Search in Rotated Sorted Array II
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // | |
| public boolean search(int[] nums, int target) { | |
| if(nums == null || nums.length == 0) return false; | |
| int left = 0, right = nums.length - 1; | |
| while(left <= right){ | |
| while(nums[left] == nums[right] && left < right){ | |
| right--; | |
| } | |
| int mid = (left + right) / 2; | |
| if(nums[mid] == target) return true; | |
| else if(nums[mid] >= nums[left]){ | |
| if(nums[left] <= target && target < nums[mid]) right = mid - 1; | |
| else left = mid + 1; | |
| } else { | |
| if(nums[mid] < target && target <= nums[right]) left = mid + 1; | |
| else right = mid - 1; | |
| } | |
| } | |
| return false; | |
| } | |
| // | |
| public boolean search(int[] A, int target) { | |
| if(A==null || A.length==0) | |
| return false; | |
| int l=0; | |
| int r=A.length-1; | |
| while(l<=r){ | |
| int m=(l+r)/2; | |
| if(A[m]==target) | |
| return true; | |
| if(A[m]>A[l]){ | |
| if(target>=A[l] && target<A[m]){ | |
| r = m-1; | |
| }else{ | |
| l = m+1; | |
| } | |
| }else if(A[m]<A[l]){ | |
| if(target>A[m] && target<=A[r]){ | |
| l = m+1; | |
| }else{ | |
| r = m-1; | |
| } | |
| }else{ | |
| l++; | |
| } | |
| } | |
| return false; | |
| } | |
| // |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment