万万没想到之聪明的编辑-头条2019笔试题
千万不要在原字符串上直接进行删除操作,否则删除操作时间复杂度(O(n)),会超时、超时、超时。
考点:双指针算法
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
while(n-- > 0) {
String str = sc.next();
char[] s = str.toCharArray();
int j = 0;
for(int i=0; i < s.length; i++) {
s[j++] = s[i];
if(j-3 >= 0 && s[j-3] == s[j-2] && s[j-2] == s[j-1]) {
j--;
}
else if(j-4 >= 0 && s[j-4] == s[j-3] && s[j-3] != s[j-2] && s[j-2] == s[j-1]) {
j--;
}
}
StringBuilder sb = new StringBuilder();
for(int k=0; k < j; k++)
sb.append(s[k]);
System.out.println(sb.toString());
}
}
}
剪绳子-头条2019笔试题
二分查找答案
时间复杂度(O(NlogL))。
计算次数: (N imes log_2^{10^9 imes 10^3} = 10^5 * log_2^{10^{12}} = 10^5 imes log10^{12}/log2 approx 12/0.3 imes 10^5 = 4.0 imes 10^6)
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
int[] arr = new int[n];
for(int i=0; i < n; i++)
arr[i] = sc.nextInt();
double l = 0, r = 1000000000D;
while(Math.abs(r-l) > 0.001) {
double mid = (l+ r) / 2.0;
int cnt = 0;
for(int i=0; i < n; i++) {
cnt += (int) ((double)arr[i] / mid);
}
if(cnt >= m) l = mid;
else r = mid;
}
// System.out.println(r);
System.out.printf("%.2f", r);
}
}