## Wednesday, November 25, 2015

### Popular Numbers in Sorted Array- 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;
}