版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
第二题
思路:每当遇到一个左括号时记录他的位置(变量count记录,初始为0),遇到左括号时count加一,遇到右括号时count减一,直到遇到此时的左括号所匹配的右括号时(当count等于0且此时已经经历过右括号时);交换此时括号对内的所有元素(第一个元素和最后一个元素交换位置,第二个元素和倒数第二个交换,依次将括号内的所有元素交换完),当遇到括号时左括号变为右括号,右括号变为左括号;然后递归交换第二个括号的内容;返回的字符串用正则表达式去掉括号就可以输出了。
代码:
public class Main2 {
/*
* 请完成下面这个函数,实现题目要求的功能 当然,你也可以不按照下面这个模板来作答,完全按照自己的想法来 ^-^ 开始写代码
******************************/
@SuppressWarnings("null")
static String resolve(String expr) {
if (expr == null || expr.length() == 0) {
return expr;
}
char[] s = expr.toCharArray();
resolveimpl(s, 0, s.length);
expr = String.valueOf(s);
String result = expr.replaceAll("[()]", "");
return result;
}
public static void swap(char[] s, int start, int end) {
char tmp = 0;
while (start < end) {
if (s[start] == '(') {
s[start] = ')';
}
if (s[end] == ')') {
s[end] = '(';
}
tmp = s[start];
s[start] = s[end];
s[end] = tmp;
start++;
end--;
}
}
public static void resolveimpl(char[] s, int start, int end) {
if (s == null || s.length == 0) {
return;
}
int sta1 = 0;
int en1 = 0;
int count = 0;
for (int i = start; i < end; i++) {
int count1 = -1;
if (s[i] == '(') {
count++;
if (count == 1) {
sta1 = i;
}
}
if (s[i] == ')') {
count--;
if (count == 0) {
count1 = 0;
en1 = i;
}
}
if (count == 0 && count1 == 0) {
swap(s, sta1, en1);
resolveimpl(s, ++sta1, en1--);
}
} // ((ab)d(ef)) 测试用例
}
/****************************** 结束写代码 ******************************/
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String res;
String _expr;
try {
_expr = in.nextLine();
} catch (Exception e) {
_expr = null;
}
res = resolve(_expr);
System.out.println(res);
}
}
第三题
没有拍照,就回忆下题意
输入一个整数n表示线程数,然后输入一个整数m表示任务数,接下来输入长度为m的数组,每个元素表示对应任务完成需要的时间(单位秒),每个线程并行运行,但是每个线程完成的任务必须在顺序上是相连的,最后输出完成这些任务需要的最短时间。
**思路:**贪心算法,写一个方法表示在t时间内是否能完成这些任务,0< t <=所有任务完成需要的总时间。然后二分查找不断缩小t的范围,直到找到最小时间。
代码:
public class Main3 {
public int temp(int thread, int task, int[] times) {
int start = 0;
int end = 0;
for (int k : times) {
end = end + k;
}
return mintime(start, end, thread, task, times);
}
public boolean isover(int t, int thread, int task, int[] times) {
int T = 0;
int j = 0;
for (int i = 0; i < thread; i++) {
T = times[j];
while (j < task && T <= t) {
j++;
if (j < task) {
T = T + times[j];
}
if (j == task) {
return true;
}
}
}
return false;
}
public int mintime(int start, int end, int thread, int task, int[] times) {
int mid = 0;
while (start < end) {
System.out.println("end=" + end + "start=" + start);
mid = (start + end) / 2;
if (isover(mid, thread, task, times)) {
end = mid;
} else {
start = mid;
if (start + 1 == end) {
return end;
}
}
}
return mid;
}
public static void main(String[] args) {
Main3 test = new Main3();
int[] times = { 5, 12, 17, 4 };
int thread = 3;
int task = times.length;
System.out.println(test.temp(thread, task, times));
}
}