Thought:
Find the largest index whose value is not more than target.
Code:
public class Solution {
public int[] searchRange(int[] A, int target) {
int[] ret = new int[2];
ret[0] = helper(A, target - 1);
ret[1] = helper(A, target);
if (ret[1] != -1 && A[ret[1]] == target) ret[0]++;
if (ret[0] != -1 && A[ret[1]] != target) ret[0] = ret[1] = -1;
return ret;
}
public int helper (int[] a, int x) {
int start = 0;
int end = a.length - 1;
int mid = (start + end)/2;
int result = -1;
while (start <= end) {
if (a[mid] > x) {
end = mid - 1;
mid = (start + end)/2;
}else {
start = mid + 1;
result = mid;
mid = (start + end)/2;
}
}
return result;
}
}
Showing posts with label Search. Show all posts
Showing posts with label Search. Show all posts
Wednesday, March 27, 2013
[LeetCode] Search in Rotated Sorted Array
Thought:
Binary Search with different condition.
Code:
public class Solution {
public int search(int[] A, int target) {
int start = 0;
int end = A.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (A[mid] == target) return mid;
if (A[start] > A[mid]) {
if (A[mid] <= target && target <= A[end]) start = mid + 1;
else end = mid - 1;
}else {
if (A[start] <= target && target <= A[mid]) end = mid - 1;
else start = mid + 1;
}
}
return - 1;
}
}
Binary Search with different condition.
Code:
public class Solution {
public int search(int[] A, int target) {
int start = 0;
int end = A.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (A[mid] == target) return mid;
if (A[start] > A[mid]) {
if (A[mid] <= target && target <= A[end]) start = mid + 1;
else end = mid - 1;
}else {
if (A[start] <= target && target <= A[mid]) end = mid - 1;
else start = mid + 1;
}
}
return - 1;
}
}
[LeetCode] Search in Rotated Sorted Array II
Thought:
Update the condition. This will change the Time to O(n).
Code:
public class Solution {
public boolean search(int[] A, int target) {
int start = 0;
int end = A.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (A[mid] == target) return true;
if (A[start] > A[mid]) {
if (A[mid] <= target && target <= A[end]) start = mid + 1;
else end = mid - 1;
}else if (A[start] < A[mid]){
if (A[start] <= target && target <= A[mid]) end = mid - 1;
else start = mid + 1;
}else {
start++;
}
}
return false;
}
}
Update the condition. This will change the Time to O(n).
Code:
public class Solution {
public boolean search(int[] A, int target) {
int start = 0;
int end = A.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (A[mid] == target) return true;
if (A[start] > A[mid]) {
if (A[mid] <= target && target <= A[end]) start = mid + 1;
else end = mid - 1;
}else if (A[start] < A[mid]){
if (A[start] <= target && target <= A[mid]) end = mid - 1;
else start = mid + 1;
}else {
start++;
}
}
return false;
}
}
Subscribe to:
Posts (Atom)