http://www.1point3acres.com/bbs/thread-147482-1-1.html
找一个sorted array里面出现次数多于N/4的元素
就是0 ,n/4, 2n/4, 3n/4, n。 然后分别左右搜索
public static boolean ifExistMoreThanQuarter(int[] sorted){
if(sorted == null || sorted.length == 0){
return false;
}. 鍥磋鎴戜滑@1point 3 acres
else if(sorted.length < 4){
return true;. 1point3acres.com/bbs
}
int mid = sorted.length / 2;
int target = sorted[mid];
int l = binarySearch(sorted, 0, mid, target, true);
int r = binarySearch(sorted, mid, sorted.length - 1, target, false); // no need, just need check sorted[l+n/4]==target
if(r - l + 1 > sorted.length / 4){
return true;
}
int leftQuarter = sorted.length / 4;
target = sorted[leftQuarter];
l = binarySearch(sorted, 0, leftQuarter, target, true);
r = binarySearch(sorted, leftQuarter, mid, target, false);
if(r - l + 1 > sorted.length / 4){
return true;
}
int rightQuarter = sorted.length * 3 / 4;
target = sorted[rightQuarter];
l = binarySearch(sorted, mid, rightQuarter, target, true);
r = binarySearch(sorted, rightQuarter, sorted.length - 1, target, false);
if(r - l + 1 > sorted.length / 4){
return true;
}
return false;
}
private static int binarySearch(int[] sorted, int left, int right, int target, boolean ifLeftSide){
while(left < right){
int mid = ifLeftSide? left + (right - left) / 2 : left + (right - left + 1) / 2;
if(ifLeftSide){
if(sorted[mid] < target){. from: 1point3acres.com/bbs
left = mid + 1;
}
else{
right = mid;
}
}
else{
if(sorted[mid] > target){
right = mid - 1;
}
else{
left = mid;
}
}
}
return left;
}
找一个sorted array里面出现次数多于N/4的元素
就是0 ,n/4, 2n/4, 3n/4, n。 然后分别左右搜索
public static boolean ifExistMoreThanQuarter(int[] sorted){
if(sorted == null || sorted.length == 0){
return false;
}. 鍥磋鎴戜滑@1point 3 acres
else if(sorted.length < 4){
return true;. 1point3acres.com/bbs
}
int mid = sorted.length / 2;
int target = sorted[mid];
int l = binarySearch(sorted, 0, mid, target, true);
int r = binarySearch(sorted, mid, sorted.length - 1, target, false); // no need, just need check sorted[l+n/4]==target
if(r - l + 1 > sorted.length / 4){
return true;
}
int leftQuarter = sorted.length / 4;
target = sorted[leftQuarter];
l = binarySearch(sorted, 0, leftQuarter, target, true);
r = binarySearch(sorted, leftQuarter, mid, target, false);
if(r - l + 1 > sorted.length / 4){
return true;
}
int rightQuarter = sorted.length * 3 / 4;
target = sorted[rightQuarter];
l = binarySearch(sorted, mid, rightQuarter, target, true);
r = binarySearch(sorted, rightQuarter, sorted.length - 1, target, false);
if(r - l + 1 > sorted.length / 4){
return true;
}
return false;
}
private static int binarySearch(int[] sorted, int left, int right, int target, boolean ifLeftSide){
while(left < right){
int mid = ifLeftSide? left + (right - left) / 2 : left + (right - left + 1) / 2;
if(ifLeftSide){
if(sorted[mid] < target){. from: 1point3acres.com/bbs
left = mid + 1;
}
else{
right = mid;
}
}
else{
if(sorted[mid] > target){
right = mid - 1;
}
else{
left = mid;
}
}
}
return left;
}