标签:
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?
Write a function to determine if a given target is in the array.
思路:
二分查找
我的代码:
public class Solution { public boolean search(int[] A, int target) { if(A == null || A.length == 0) return false; int left = 0; int right = A.length - 1; while(left <= right) { int mid = (left + right)/2; if(A[mid] == target) return true; if(A[mid] == A[left]) { left++; continue; } if(A[mid] == A[right]) { right--; continue; } if(A[left] <= A[mid]) { if(A[left] > target || A[mid] < target) left = mid + 1; else right = mid - 1; } else { if(A[right] < target || A[mid] > target) right = mid - 1; else left = 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 mid = l + (r - l) / 2; if (A[mid] == target) { return true; } // left sort if (A[mid] > A[l]) { // out of range. if (target > A[mid] || target < A[l]) { l = mid + 1; } else { r = mid - 1; } // right sort. } else if (A[mid] < A[l]) { // out of range. if (target < A[mid] || target > A[r]) { r = mid - 1; } else { l = mid + 1; } } else { // move one node. l++; } } return false; }
学习之处:
Search in Rotated Sorted Array II
标签:
原文地址:http://www.cnblogs.com/sunshisonghit/p/4321760.html